babylon.max.js 3.6 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. var absX = Math.abs(this.x);
  1403. var absY = Math.abs(this.y);
  1404. if (absX !== absY) {
  1405. return true;
  1406. }
  1407. var absZ = Math.abs(this.z);
  1408. if (absX !== absZ) {
  1409. return true;
  1410. }
  1411. if (absY !== absZ) {
  1412. return true;
  1413. }
  1414. return false;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. // Properties
  1420. /**
  1421. * Returns the length of the Vector3 (float).
  1422. */
  1423. Vector3.prototype.length = function () {
  1424. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1425. };
  1426. /**
  1427. * Returns the squared length of the Vector3 (float).
  1428. */
  1429. Vector3.prototype.lengthSquared = function () {
  1430. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1431. };
  1432. // Methods
  1433. /**
  1434. * Normalize the current Vector3.
  1435. * Returns the updated Vector3.
  1436. */
  1437. Vector3.prototype.normalize = function () {
  1438. var len = this.length();
  1439. if (len === 0 || len === 1.0)
  1440. return this;
  1441. var num = 1.0 / len;
  1442. this.x *= num;
  1443. this.y *= num;
  1444. this.z *= num;
  1445. return this;
  1446. };
  1447. /**
  1448. * Returns a new Vector3 copied from the current Vector3.
  1449. */
  1450. Vector3.prototype.clone = function () {
  1451. return new Vector3(this.x, this.y, this.z);
  1452. };
  1453. /**
  1454. * Copies the passed vector coordinates to the current Vector3 ones.
  1455. * Returns the updated Vector3.
  1456. */
  1457. Vector3.prototype.copyFrom = function (source) {
  1458. this.x = source.x;
  1459. this.y = source.y;
  1460. this.z = source.z;
  1461. return this;
  1462. };
  1463. /**
  1464. * Copies the passed floats to the current Vector3 coordinates.
  1465. * Returns the updated Vector3.
  1466. */
  1467. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1468. this.x = x;
  1469. this.y = y;
  1470. this.z = z;
  1471. return this;
  1472. };
  1473. /**
  1474. * Copies the passed floats to the current Vector3 coordinates.
  1475. * Returns the updated Vector3.
  1476. */
  1477. Vector3.prototype.set = function (x, y, z) {
  1478. return this.copyFromFloats(x, y, z);
  1479. };
  1480. // Statics
  1481. /**
  1482. *
  1483. */
  1484. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1485. var d0 = Vector3.Dot(vector0, axis) - size;
  1486. var d1 = Vector3.Dot(vector1, axis) - size;
  1487. var s = d0 / (d0 - d1);
  1488. return s;
  1489. };
  1490. /**
  1491. * Returns a new Vector3 set from the index "offset" of the passed array.
  1492. */
  1493. Vector3.FromArray = function (array, offset) {
  1494. if (!offset) {
  1495. offset = 0;
  1496. }
  1497. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1498. };
  1499. /**
  1500. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1501. * This function is deprecated. Use FromArray instead.
  1502. */
  1503. Vector3.FromFloatArray = function (array, offset) {
  1504. return Vector3.FromArray(array, offset);
  1505. };
  1506. /**
  1507. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1508. */
  1509. Vector3.FromArrayToRef = function (array, offset, result) {
  1510. result.x = array[offset];
  1511. result.y = array[offset + 1];
  1512. result.z = array[offset + 2];
  1513. };
  1514. /**
  1515. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1516. * This function is deprecated. Use FromArrayToRef instead.
  1517. */
  1518. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1519. return Vector3.FromArrayToRef(array, offset, result);
  1520. };
  1521. /**
  1522. * Sets the passed vector "result" with the passed floats.
  1523. */
  1524. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1525. result.x = x;
  1526. result.y = y;
  1527. result.z = z;
  1528. };
  1529. /**
  1530. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1531. */
  1532. Vector3.Zero = function () {
  1533. return new Vector3(0.0, 0.0, 0.0);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1537. */
  1538. Vector3.One = function () {
  1539. return new Vector3(1.0, 1.0, 1.0);
  1540. };
  1541. /**
  1542. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1543. */
  1544. Vector3.Up = function () {
  1545. return new Vector3(0.0, 1.0, 0.0);
  1546. };
  1547. /**
  1548. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1549. */
  1550. Vector3.Forward = function () {
  1551. return new Vector3(0.0, 0.0, 1.0);
  1552. };
  1553. /**
  1554. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1555. */
  1556. Vector3.Right = function () {
  1557. return new Vector3(1.0, 0.0, 0.0);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1561. */
  1562. Vector3.Left = function () {
  1563. return new Vector3(-1.0, 0.0, 0.0);
  1564. };
  1565. /**
  1566. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1567. * This method computes tranformed coordinates only, not transformed direction vectors.
  1568. */
  1569. Vector3.TransformCoordinates = function (vector, transformation) {
  1570. var result = Vector3.Zero();
  1571. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1572. return result;
  1573. };
  1574. /**
  1575. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1576. * This method computes tranformed coordinates only, not transformed direction vectors.
  1577. */
  1578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1583. result.x = x / w;
  1584. result.y = y / w;
  1585. result.z = z / w;
  1586. };
  1587. /**
  1588. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1589. * This method computes tranformed coordinates only, not transformed direction vectors.
  1590. */
  1591. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1592. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1593. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1594. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1595. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1596. result.x = rx / rw;
  1597. result.y = ry / rw;
  1598. result.z = rz / rw;
  1599. };
  1600. /**
  1601. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1602. * This methods computes transformed normalized direction vectors only.
  1603. */
  1604. Vector3.TransformNormal = function (vector, transformation) {
  1605. var result = Vector3.Zero();
  1606. Vector3.TransformNormalToRef(vector, transformation, result);
  1607. return result;
  1608. };
  1609. /**
  1610. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1611. * This methods computes transformed normalized direction vectors only.
  1612. */
  1613. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1614. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1615. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1616. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1617. result.x = x;
  1618. result.y = y;
  1619. result.z = z;
  1620. };
  1621. /**
  1622. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1623. * This methods computes transformed normalized direction vectors only.
  1624. */
  1625. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1626. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1627. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1628. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1629. };
  1630. /**
  1631. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1632. */
  1633. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1634. var squared = amount * amount;
  1635. var cubed = amount * squared;
  1636. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1637. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1638. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1639. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1640. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1641. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1642. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1643. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1644. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1645. return new Vector3(x, y, z);
  1646. };
  1647. /**
  1648. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1649. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1650. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1651. */
  1652. Vector3.Clamp = function (value, min, max) {
  1653. var x = value.x;
  1654. x = (x > max.x) ? max.x : x;
  1655. x = (x < min.x) ? min.x : x;
  1656. var y = value.y;
  1657. y = (y > max.y) ? max.y : y;
  1658. y = (y < min.y) ? min.y : y;
  1659. var z = value.z;
  1660. z = (z > max.z) ? max.z : z;
  1661. z = (z < min.z) ? min.z : z;
  1662. return new Vector3(x, y, z);
  1663. };
  1664. /**
  1665. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1666. */
  1667. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1668. var squared = amount * amount;
  1669. var cubed = amount * squared;
  1670. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1671. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1672. var part3 = (cubed - (2.0 * squared)) + amount;
  1673. var part4 = cubed - squared;
  1674. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1675. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1676. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1677. return new Vector3(x, y, z);
  1678. };
  1679. /**
  1680. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1681. */
  1682. Vector3.Lerp = function (start, end, amount) {
  1683. var result = new Vector3(0, 0, 0);
  1684. Vector3.LerpToRef(start, end, amount, result);
  1685. return result;
  1686. };
  1687. /**
  1688. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1689. */
  1690. Vector3.LerpToRef = function (start, end, amount, result) {
  1691. result.x = start.x + ((end.x - start.x) * amount);
  1692. result.y = start.y + ((end.y - start.y) * amount);
  1693. result.z = start.z + ((end.z - start.z) * amount);
  1694. };
  1695. /**
  1696. * Returns the dot product (float) between the vectors "left" and "right".
  1697. */
  1698. Vector3.Dot = function (left, right) {
  1699. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1700. };
  1701. /**
  1702. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1703. * The cross product is then orthogonal to both "left" and "right".
  1704. */
  1705. Vector3.Cross = function (left, right) {
  1706. var result = Vector3.Zero();
  1707. Vector3.CrossToRef(left, right, result);
  1708. return result;
  1709. };
  1710. /**
  1711. * Sets the passed vector "result" with the cross product of "left" and "right".
  1712. * The cross product is then orthogonal to both "left" and "right".
  1713. */
  1714. Vector3.CrossToRef = function (left, right, result) {
  1715. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1716. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1717. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1718. result.copyFrom(MathTmp.Vector3[0]);
  1719. };
  1720. /**
  1721. * Returns a new Vector3 as the normalization of the passed vector.
  1722. */
  1723. Vector3.Normalize = function (vector) {
  1724. var result = Vector3.Zero();
  1725. Vector3.NormalizeToRef(vector, result);
  1726. return result;
  1727. };
  1728. /**
  1729. * Sets the passed vector "result" with the normalization of the passed first vector.
  1730. */
  1731. Vector3.NormalizeToRef = function (vector, result) {
  1732. result.copyFrom(vector);
  1733. result.normalize();
  1734. };
  1735. Vector3.Project = function (vector, world, transform, viewport) {
  1736. var cw = viewport.width;
  1737. var ch = viewport.height;
  1738. var cx = viewport.x;
  1739. var cy = viewport.y;
  1740. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1741. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1742. var matrix = MathTmp.Matrix[0];
  1743. world.multiplyToRef(transform, matrix);
  1744. matrix.multiplyToRef(viewportMatrix, matrix);
  1745. return Vector3.TransformCoordinates(vector, matrix);
  1746. };
  1747. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1748. var matrix = MathTmp.Matrix[0];
  1749. world.multiplyToRef(transform, matrix);
  1750. matrix.invert();
  1751. source.x = source.x / viewportWidth * 2 - 1;
  1752. source.y = -(source.y / viewportHeight * 2 - 1);
  1753. var vector = Vector3.TransformCoordinates(source, matrix);
  1754. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1755. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1756. vector = vector.scale(1.0 / num);
  1757. }
  1758. return vector;
  1759. };
  1760. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1761. var matrix = MathTmp.Matrix[0];
  1762. world.multiplyToRef(view, matrix);
  1763. matrix.multiplyToRef(projection, matrix);
  1764. matrix.invert();
  1765. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1766. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1767. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1768. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1769. vector = vector.scale(1.0 / num);
  1770. }
  1771. return vector;
  1772. };
  1773. Vector3.Minimize = function (left, right) {
  1774. var min = left.clone();
  1775. min.MinimizeInPlace(right);
  1776. return min;
  1777. };
  1778. Vector3.Maximize = function (left, right) {
  1779. var max = left.clone();
  1780. max.MaximizeInPlace(right);
  1781. return max;
  1782. };
  1783. /**
  1784. * Returns the distance (float) between the vectors "value1" and "value2".
  1785. */
  1786. Vector3.Distance = function (value1, value2) {
  1787. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1788. };
  1789. /**
  1790. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1791. */
  1792. Vector3.DistanceSquared = function (value1, value2) {
  1793. var x = value1.x - value2.x;
  1794. var y = value1.y - value2.y;
  1795. var z = value1.z - value2.z;
  1796. return (x * x) + (y * y) + (z * z);
  1797. };
  1798. /**
  1799. * Returns a new Vector3 located at the center between "value1" and "value2".
  1800. */
  1801. Vector3.Center = function (value1, value2) {
  1802. var center = value1.add(value2);
  1803. center.scaleInPlace(0.5);
  1804. return center;
  1805. };
  1806. /**
  1807. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1808. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1809. * to something in order to rotate it from its local system to the given target system.
  1810. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1811. * Returns a new Vector3.
  1812. */
  1813. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1814. var rotation = Vector3.Zero();
  1815. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1816. return rotation;
  1817. };
  1818. /**
  1819. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1820. */
  1821. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1822. var quat = MathTmp.Quaternion[0];
  1823. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1824. quat.toEulerAnglesToRef(ref);
  1825. };
  1826. return Vector3;
  1827. }());
  1828. BABYLON.Vector3 = Vector3;
  1829. //Vector4 class created for EulerAngle class conversion to Quaternion
  1830. var Vector4 = /** @class */ (function () {
  1831. /**
  1832. * Creates a Vector4 object from the passed floats.
  1833. */
  1834. function Vector4(x, y, z, w) {
  1835. this.x = x;
  1836. this.y = y;
  1837. this.z = z;
  1838. this.w = w;
  1839. }
  1840. /**
  1841. * Returns the string with the Vector4 coordinates.
  1842. */
  1843. Vector4.prototype.toString = function () {
  1844. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1845. };
  1846. /**
  1847. * Returns the string "Vector4".
  1848. */
  1849. Vector4.prototype.getClassName = function () {
  1850. return "Vector4";
  1851. };
  1852. /**
  1853. * Returns the Vector4 hash code.
  1854. */
  1855. Vector4.prototype.getHashCode = function () {
  1856. var hash = this.x || 0;
  1857. hash = (hash * 397) ^ (this.y || 0);
  1858. hash = (hash * 397) ^ (this.z || 0);
  1859. hash = (hash * 397) ^ (this.w || 0);
  1860. return hash;
  1861. };
  1862. // Operators
  1863. /**
  1864. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1865. */
  1866. Vector4.prototype.asArray = function () {
  1867. var result = new Array();
  1868. this.toArray(result, 0);
  1869. return result;
  1870. };
  1871. /**
  1872. * Populates the passed array from the passed index with the Vector4 coordinates.
  1873. * Returns the Vector4.
  1874. */
  1875. Vector4.prototype.toArray = function (array, index) {
  1876. if (index === undefined) {
  1877. index = 0;
  1878. }
  1879. array[index] = this.x;
  1880. array[index + 1] = this.y;
  1881. array[index + 2] = this.z;
  1882. array[index + 3] = this.w;
  1883. return this;
  1884. };
  1885. /**
  1886. * Adds the passed vector to the current Vector4.
  1887. * Returns the updated Vector4.
  1888. */
  1889. Vector4.prototype.addInPlace = function (otherVector) {
  1890. this.x += otherVector.x;
  1891. this.y += otherVector.y;
  1892. this.z += otherVector.z;
  1893. this.w += otherVector.w;
  1894. return this;
  1895. };
  1896. /**
  1897. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1898. */
  1899. Vector4.prototype.add = function (otherVector) {
  1900. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1901. };
  1902. /**
  1903. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1904. * Returns the current Vector4.
  1905. */
  1906. Vector4.prototype.addToRef = function (otherVector, result) {
  1907. result.x = this.x + otherVector.x;
  1908. result.y = this.y + otherVector.y;
  1909. result.z = this.z + otherVector.z;
  1910. result.w = this.w + otherVector.w;
  1911. return this;
  1912. };
  1913. /**
  1914. * Subtract in place the passed vector from the current Vector4.
  1915. * Returns the updated Vector4.
  1916. */
  1917. Vector4.prototype.subtractInPlace = function (otherVector) {
  1918. this.x -= otherVector.x;
  1919. this.y -= otherVector.y;
  1920. this.z -= otherVector.z;
  1921. this.w -= otherVector.w;
  1922. return this;
  1923. };
  1924. /**
  1925. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1926. */
  1927. Vector4.prototype.subtract = function (otherVector) {
  1928. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1929. };
  1930. /**
  1931. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1932. * Returns the current Vector4.
  1933. */
  1934. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1935. result.x = this.x - otherVector.x;
  1936. result.y = this.y - otherVector.y;
  1937. result.z = this.z - otherVector.z;
  1938. result.w = this.w - otherVector.w;
  1939. return this;
  1940. };
  1941. /**
  1942. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1943. */
  1944. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1945. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1946. };
  1947. /**
  1948. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1949. * Returns the current Vector4.
  1950. */
  1951. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1952. result.x = this.x - x;
  1953. result.y = this.y - y;
  1954. result.z = this.z - z;
  1955. result.w = this.w - w;
  1956. return this;
  1957. };
  1958. /**
  1959. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1960. */
  1961. Vector4.prototype.negate = function () {
  1962. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1963. };
  1964. /**
  1965. * Multiplies the current Vector4 coordinates by scale (float).
  1966. * Returns the updated Vector4.
  1967. */
  1968. Vector4.prototype.scaleInPlace = function (scale) {
  1969. this.x *= scale;
  1970. this.y *= scale;
  1971. this.z *= scale;
  1972. this.w *= scale;
  1973. return this;
  1974. };
  1975. /**
  1976. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1977. */
  1978. Vector4.prototype.scale = function (scale) {
  1979. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1980. };
  1981. /**
  1982. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1983. * Returns the current Vector4.
  1984. */
  1985. Vector4.prototype.scaleToRef = function (scale, result) {
  1986. result.x = this.x * scale;
  1987. result.y = this.y * scale;
  1988. result.z = this.z * scale;
  1989. result.w = this.w * scale;
  1990. return this;
  1991. };
  1992. /**
  1993. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1994. */
  1995. Vector4.prototype.equals = function (otherVector) {
  1996. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1997. };
  1998. /**
  1999. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2000. */
  2001. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2002. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2003. return otherVector
  2004. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2005. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2006. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2007. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2008. };
  2009. /**
  2010. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2011. */
  2012. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2013. return this.x === x && this.y === y && this.z === z && this.w === w;
  2014. };
  2015. /**
  2016. * Multiplies in place the current Vector4 by the passed one.
  2017. * Returns the updated Vector4.
  2018. */
  2019. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2020. this.x *= otherVector.x;
  2021. this.y *= otherVector.y;
  2022. this.z *= otherVector.z;
  2023. this.w *= otherVector.w;
  2024. return this;
  2025. };
  2026. /**
  2027. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2028. */
  2029. Vector4.prototype.multiply = function (otherVector) {
  2030. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2031. };
  2032. /**
  2033. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2034. * Returns the current Vector4.
  2035. */
  2036. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2037. result.x = this.x * otherVector.x;
  2038. result.y = this.y * otherVector.y;
  2039. result.z = this.z * otherVector.z;
  2040. result.w = this.w * otherVector.w;
  2041. return this;
  2042. };
  2043. /**
  2044. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2045. */
  2046. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2047. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2048. };
  2049. /**
  2050. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2051. */
  2052. Vector4.prototype.divide = function (otherVector) {
  2053. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2054. };
  2055. /**
  2056. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2057. * Returns the current Vector4.
  2058. */
  2059. Vector4.prototype.divideToRef = function (otherVector, result) {
  2060. result.x = this.x / otherVector.x;
  2061. result.y = this.y / otherVector.y;
  2062. result.z = this.z / otherVector.z;
  2063. result.w = this.w / otherVector.w;
  2064. return this;
  2065. };
  2066. /**
  2067. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2068. */
  2069. Vector4.prototype.MinimizeInPlace = function (other) {
  2070. if (other.x < this.x)
  2071. this.x = other.x;
  2072. if (other.y < this.y)
  2073. this.y = other.y;
  2074. if (other.z < this.z)
  2075. this.z = other.z;
  2076. if (other.w < this.w)
  2077. this.w = other.w;
  2078. return this;
  2079. };
  2080. /**
  2081. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2082. */
  2083. Vector4.prototype.MaximizeInPlace = function (other) {
  2084. if (other.x > this.x)
  2085. this.x = other.x;
  2086. if (other.y > this.y)
  2087. this.y = other.y;
  2088. if (other.z > this.z)
  2089. this.z = other.z;
  2090. if (other.w > this.w)
  2091. this.w = other.w;
  2092. return this;
  2093. };
  2094. // Properties
  2095. /**
  2096. * Returns the Vector4 length (float).
  2097. */
  2098. Vector4.prototype.length = function () {
  2099. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2100. };
  2101. /**
  2102. * Returns the Vector4 squared length (float).
  2103. */
  2104. Vector4.prototype.lengthSquared = function () {
  2105. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2106. };
  2107. // Methods
  2108. /**
  2109. * Normalizes in place the Vector4.
  2110. * Returns the updated Vector4.
  2111. */
  2112. Vector4.prototype.normalize = function () {
  2113. var len = this.length();
  2114. if (len === 0)
  2115. return this;
  2116. var num = 1.0 / len;
  2117. this.x *= num;
  2118. this.y *= num;
  2119. this.z *= num;
  2120. this.w *= num;
  2121. return this;
  2122. };
  2123. /**
  2124. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2125. */
  2126. Vector4.prototype.toVector3 = function () {
  2127. return new Vector3(this.x, this.y, this.z);
  2128. };
  2129. /**
  2130. * Returns a new Vector4 copied from the current one.
  2131. */
  2132. Vector4.prototype.clone = function () {
  2133. return new Vector4(this.x, this.y, this.z, this.w);
  2134. };
  2135. /**
  2136. * Updates the current Vector4 with the passed one coordinates.
  2137. * Returns the updated Vector4.
  2138. */
  2139. Vector4.prototype.copyFrom = function (source) {
  2140. this.x = source.x;
  2141. this.y = source.y;
  2142. this.z = source.z;
  2143. this.w = source.w;
  2144. return this;
  2145. };
  2146. /**
  2147. * Updates the current Vector4 coordinates with the passed floats.
  2148. * Returns the updated Vector4.
  2149. */
  2150. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2151. this.x = x;
  2152. this.y = y;
  2153. this.z = z;
  2154. this.w = w;
  2155. return this;
  2156. };
  2157. /**
  2158. * Updates the current Vector4 coordinates with the passed floats.
  2159. * Returns the updated Vector4.
  2160. */
  2161. Vector4.prototype.set = function (x, y, z, w) {
  2162. return this.copyFromFloats(x, y, z, w);
  2163. };
  2164. // Statics
  2165. /**
  2166. * Returns a new Vector4 set from the starting index of the passed array.
  2167. */
  2168. Vector4.FromArray = function (array, offset) {
  2169. if (!offset) {
  2170. offset = 0;
  2171. }
  2172. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2173. };
  2174. /**
  2175. * Updates the passed vector "result" from the starting index of the passed array.
  2176. */
  2177. Vector4.FromArrayToRef = function (array, offset, result) {
  2178. result.x = array[offset];
  2179. result.y = array[offset + 1];
  2180. result.z = array[offset + 2];
  2181. result.w = array[offset + 3];
  2182. };
  2183. /**
  2184. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2185. */
  2186. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2187. Vector4.FromArrayToRef(array, offset, result);
  2188. };
  2189. /**
  2190. * Updates the passed vector "result" coordinates from the passed floats.
  2191. */
  2192. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2193. result.x = x;
  2194. result.y = y;
  2195. result.z = z;
  2196. result.w = w;
  2197. };
  2198. /**
  2199. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2200. */
  2201. Vector4.Zero = function () {
  2202. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2203. };
  2204. /**
  2205. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2206. */
  2207. Vector4.One = function () {
  2208. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2209. };
  2210. /**
  2211. * Returns a new normalized Vector4 from the passed one.
  2212. */
  2213. Vector4.Normalize = function (vector) {
  2214. var result = Vector4.Zero();
  2215. Vector4.NormalizeToRef(vector, result);
  2216. return result;
  2217. };
  2218. /**
  2219. * Updates the passed vector "result" from the normalization of the passed one.
  2220. */
  2221. Vector4.NormalizeToRef = function (vector, result) {
  2222. result.copyFrom(vector);
  2223. result.normalize();
  2224. };
  2225. Vector4.Minimize = function (left, right) {
  2226. var min = left.clone();
  2227. min.MinimizeInPlace(right);
  2228. return min;
  2229. };
  2230. Vector4.Maximize = function (left, right) {
  2231. var max = left.clone();
  2232. max.MaximizeInPlace(right);
  2233. return max;
  2234. };
  2235. /**
  2236. * Returns the distance (float) between the vectors "value1" and "value2".
  2237. */
  2238. Vector4.Distance = function (value1, value2) {
  2239. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2240. };
  2241. /**
  2242. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2243. */
  2244. Vector4.DistanceSquared = function (value1, value2) {
  2245. var x = value1.x - value2.x;
  2246. var y = value1.y - value2.y;
  2247. var z = value1.z - value2.z;
  2248. var w = value1.w - value2.w;
  2249. return (x * x) + (y * y) + (z * z) + (w * w);
  2250. };
  2251. /**
  2252. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2253. */
  2254. Vector4.Center = function (value1, value2) {
  2255. var center = value1.add(value2);
  2256. center.scaleInPlace(0.5);
  2257. return center;
  2258. };
  2259. /**
  2260. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2261. * This methods computes transformed normalized direction vectors only.
  2262. */
  2263. Vector4.TransformNormal = function (vector, transformation) {
  2264. var result = Vector4.Zero();
  2265. Vector4.TransformNormalToRef(vector, transformation, result);
  2266. return result;
  2267. };
  2268. /**
  2269. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2270. * This methods computes transformed normalized direction vectors only.
  2271. */
  2272. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2273. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2274. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2275. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2276. result.x = x;
  2277. result.y = y;
  2278. result.z = z;
  2279. result.w = vector.w;
  2280. };
  2281. /**
  2282. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2283. * This methods computes transformed normalized direction vectors only.
  2284. */
  2285. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2286. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2287. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2288. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2289. result.w = w;
  2290. };
  2291. return Vector4;
  2292. }());
  2293. BABYLON.Vector4 = Vector4;
  2294. var Size = /** @class */ (function () {
  2295. /**
  2296. * Creates a Size object from the passed width and height (floats).
  2297. */
  2298. function Size(width, height) {
  2299. this.width = width;
  2300. this.height = height;
  2301. }
  2302. // Returns a string with the Size width and height.
  2303. Size.prototype.toString = function () {
  2304. return "{W: " + this.width + ", H: " + this.height + "}";
  2305. };
  2306. /**
  2307. * Returns the string "Size"
  2308. */
  2309. Size.prototype.getClassName = function () {
  2310. return "Size";
  2311. };
  2312. /**
  2313. * Returns the Size hash code.
  2314. */
  2315. Size.prototype.getHashCode = function () {
  2316. var hash = this.width || 0;
  2317. hash = (hash * 397) ^ (this.height || 0);
  2318. return hash;
  2319. };
  2320. /**
  2321. * Updates the current size from the passed one.
  2322. * Returns the updated Size.
  2323. */
  2324. Size.prototype.copyFrom = function (src) {
  2325. this.width = src.width;
  2326. this.height = src.height;
  2327. };
  2328. /**
  2329. * Updates in place the current Size from the passed floats.
  2330. * Returns the updated Size.
  2331. */
  2332. Size.prototype.copyFromFloats = function (width, height) {
  2333. this.width = width;
  2334. this.height = height;
  2335. return this;
  2336. };
  2337. /**
  2338. * Updates in place the current Size from the passed floats.
  2339. * Returns the updated Size.
  2340. */
  2341. Size.prototype.set = function (width, height) {
  2342. return this.copyFromFloats(width, height);
  2343. };
  2344. /**
  2345. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2346. */
  2347. Size.prototype.multiplyByFloats = function (w, h) {
  2348. return new Size(this.width * w, this.height * h);
  2349. };
  2350. /**
  2351. * Returns a new Size copied from the passed one.
  2352. */
  2353. Size.prototype.clone = function () {
  2354. return new Size(this.width, this.height);
  2355. };
  2356. /**
  2357. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2358. */
  2359. Size.prototype.equals = function (other) {
  2360. if (!other) {
  2361. return false;
  2362. }
  2363. return (this.width === other.width) && (this.height === other.height);
  2364. };
  2365. Object.defineProperty(Size.prototype, "surface", {
  2366. /**
  2367. * Returns the surface of the Size : width * height (float).
  2368. */
  2369. get: function () {
  2370. return this.width * this.height;
  2371. },
  2372. enumerable: true,
  2373. configurable: true
  2374. });
  2375. /**
  2376. * Returns a new Size set to (0.0, 0.0)
  2377. */
  2378. Size.Zero = function () {
  2379. return new Size(0.0, 0.0);
  2380. };
  2381. /**
  2382. * Returns a new Size set as the addition result of the current Size and the passed one.
  2383. */
  2384. Size.prototype.add = function (otherSize) {
  2385. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2386. return r;
  2387. };
  2388. /**
  2389. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2390. */
  2391. Size.prototype.subtract = function (otherSize) {
  2392. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2393. return r;
  2394. };
  2395. /**
  2396. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2397. */
  2398. Size.Lerp = function (start, end, amount) {
  2399. var w = start.width + ((end.width - start.width) * amount);
  2400. var h = start.height + ((end.height - start.height) * amount);
  2401. return new Size(w, h);
  2402. };
  2403. return Size;
  2404. }());
  2405. BABYLON.Size = Size;
  2406. var Quaternion = /** @class */ (function () {
  2407. /**
  2408. * Creates a new Quaternion from the passed floats.
  2409. */
  2410. function Quaternion(x, y, z, w) {
  2411. if (x === void 0) { x = 0.0; }
  2412. if (y === void 0) { y = 0.0; }
  2413. if (z === void 0) { z = 0.0; }
  2414. if (w === void 0) { w = 1.0; }
  2415. this.x = x;
  2416. this.y = y;
  2417. this.z = z;
  2418. this.w = w;
  2419. }
  2420. /**
  2421. * Returns a string with the Quaternion coordinates.
  2422. */
  2423. Quaternion.prototype.toString = function () {
  2424. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2425. };
  2426. /**
  2427. * Returns the string "Quaternion".
  2428. */
  2429. Quaternion.prototype.getClassName = function () {
  2430. return "Quaternion";
  2431. };
  2432. /**
  2433. * Returns the Quaternion hash code.
  2434. */
  2435. Quaternion.prototype.getHashCode = function () {
  2436. var hash = this.x || 0;
  2437. hash = (hash * 397) ^ (this.y || 0);
  2438. hash = (hash * 397) ^ (this.z || 0);
  2439. hash = (hash * 397) ^ (this.w || 0);
  2440. return hash;
  2441. };
  2442. /**
  2443. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2444. */
  2445. Quaternion.prototype.asArray = function () {
  2446. return [this.x, this.y, this.z, this.w];
  2447. };
  2448. /**
  2449. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2450. */
  2451. Quaternion.prototype.equals = function (otherQuaternion) {
  2452. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2453. };
  2454. /**
  2455. * Returns a new Quaternion copied from the current one.
  2456. */
  2457. Quaternion.prototype.clone = function () {
  2458. return new Quaternion(this.x, this.y, this.z, this.w);
  2459. };
  2460. /**
  2461. * Updates the current Quaternion from the passed one coordinates.
  2462. * Returns the updated Quaterion.
  2463. */
  2464. Quaternion.prototype.copyFrom = function (other) {
  2465. this.x = other.x;
  2466. this.y = other.y;
  2467. this.z = other.z;
  2468. this.w = other.w;
  2469. return this;
  2470. };
  2471. /**
  2472. * Updates the current Quaternion from the passed float coordinates.
  2473. * Returns the updated Quaterion.
  2474. */
  2475. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2476. this.x = x;
  2477. this.y = y;
  2478. this.z = z;
  2479. this.w = w;
  2480. return this;
  2481. };
  2482. /**
  2483. * Updates the current Quaternion from the passed float coordinates.
  2484. * Returns the updated Quaterion.
  2485. */
  2486. Quaternion.prototype.set = function (x, y, z, w) {
  2487. return this.copyFromFloats(x, y, z, w);
  2488. };
  2489. /**
  2490. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2491. */
  2492. Quaternion.prototype.add = function (other) {
  2493. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2494. };
  2495. /**
  2496. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2497. */
  2498. Quaternion.prototype.subtract = function (other) {
  2499. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2500. };
  2501. /**
  2502. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2503. */
  2504. Quaternion.prototype.scale = function (value) {
  2505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2506. };
  2507. /**
  2508. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2509. */
  2510. Quaternion.prototype.multiply = function (q1) {
  2511. var result = new Quaternion(0, 0, 0, 1.0);
  2512. this.multiplyToRef(q1, result);
  2513. return result;
  2514. };
  2515. /**
  2516. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2517. * Returns the current Quaternion.
  2518. */
  2519. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2520. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2521. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2522. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2523. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2524. result.copyFromFloats(x, y, z, w);
  2525. return this;
  2526. };
  2527. /**
  2528. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2529. * Returns the updated Quaternion.
  2530. */
  2531. Quaternion.prototype.multiplyInPlace = function (q1) {
  2532. this.multiplyToRef(q1, this);
  2533. return this;
  2534. };
  2535. /**
  2536. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2537. * Returns the current Quaternion.
  2538. */
  2539. Quaternion.prototype.conjugateToRef = function (ref) {
  2540. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2541. return this;
  2542. };
  2543. /**
  2544. * Conjugates in place the current Quaternion.
  2545. * Returns the updated Quaternion.
  2546. */
  2547. Quaternion.prototype.conjugateInPlace = function () {
  2548. this.x *= -1;
  2549. this.y *= -1;
  2550. this.z *= -1;
  2551. return this;
  2552. };
  2553. /**
  2554. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2555. */
  2556. Quaternion.prototype.conjugate = function () {
  2557. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2558. return result;
  2559. };
  2560. /**
  2561. * Returns the Quaternion length (float).
  2562. */
  2563. Quaternion.prototype.length = function () {
  2564. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2565. };
  2566. /**
  2567. * Normalize in place the current Quaternion.
  2568. * Returns the updated Quaternion.
  2569. */
  2570. Quaternion.prototype.normalize = function () {
  2571. var length = 1.0 / this.length();
  2572. this.x *= length;
  2573. this.y *= length;
  2574. this.z *= length;
  2575. this.w *= length;
  2576. return this;
  2577. };
  2578. /**
  2579. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2580. */
  2581. Quaternion.prototype.toEulerAngles = function (order) {
  2582. if (order === void 0) { order = "YZX"; }
  2583. var result = Vector3.Zero();
  2584. this.toEulerAnglesToRef(result, order);
  2585. return result;
  2586. };
  2587. /**
  2588. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2589. * Returns the current Quaternion.
  2590. */
  2591. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2592. if (order === void 0) { order = "YZX"; }
  2593. var qz = this.z;
  2594. var qx = this.x;
  2595. var qy = this.y;
  2596. var qw = this.w;
  2597. var sqw = qw * qw;
  2598. var sqz = qz * qz;
  2599. var sqx = qx * qx;
  2600. var sqy = qy * qy;
  2601. var zAxisY = qy * qz - qx * qw;
  2602. var limit = .4999999;
  2603. if (zAxisY < -limit) {
  2604. result.y = 2 * Math.atan2(qy, qw);
  2605. result.x = Math.PI / 2;
  2606. result.z = 0;
  2607. }
  2608. else if (zAxisY > limit) {
  2609. result.y = 2 * Math.atan2(qy, qw);
  2610. result.x = -Math.PI / 2;
  2611. result.z = 0;
  2612. }
  2613. else {
  2614. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2615. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2616. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2617. }
  2618. return this;
  2619. };
  2620. /**
  2621. * Updates the passed rotation matrix with the current Quaternion values.
  2622. * Returns the current Quaternion.
  2623. */
  2624. Quaternion.prototype.toRotationMatrix = function (result) {
  2625. var xx = this.x * this.x;
  2626. var yy = this.y * this.y;
  2627. var zz = this.z * this.z;
  2628. var xy = this.x * this.y;
  2629. var zw = this.z * this.w;
  2630. var zx = this.z * this.x;
  2631. var yw = this.y * this.w;
  2632. var yz = this.y * this.z;
  2633. var xw = this.x * this.w;
  2634. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2635. result.m[1] = 2.0 * (xy + zw);
  2636. result.m[2] = 2.0 * (zx - yw);
  2637. result.m[3] = 0;
  2638. result.m[4] = 2.0 * (xy - zw);
  2639. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2640. result.m[6] = 2.0 * (yz + xw);
  2641. result.m[7] = 0;
  2642. result.m[8] = 2.0 * (zx + yw);
  2643. result.m[9] = 2.0 * (yz - xw);
  2644. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2645. result.m[11] = 0;
  2646. result.m[12] = 0;
  2647. result.m[13] = 0;
  2648. result.m[14] = 0;
  2649. result.m[15] = 1.0;
  2650. result._markAsUpdated();
  2651. return this;
  2652. };
  2653. /**
  2654. * Updates the current Quaternion from the passed rotation matrix values.
  2655. * Returns the updated Quaternion.
  2656. */
  2657. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2658. Quaternion.FromRotationMatrixToRef(matrix, this);
  2659. return this;
  2660. };
  2661. // Statics
  2662. /**
  2663. * Returns a new Quaternion set from the passed rotation matrix values.
  2664. */
  2665. Quaternion.FromRotationMatrix = function (matrix) {
  2666. var result = new Quaternion();
  2667. Quaternion.FromRotationMatrixToRef(matrix, result);
  2668. return result;
  2669. };
  2670. /**
  2671. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2672. */
  2673. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2674. var data = matrix.m;
  2675. var m11 = data[0], m12 = data[4], m13 = data[8];
  2676. var m21 = data[1], m22 = data[5], m23 = data[9];
  2677. var m31 = data[2], m32 = data[6], m33 = data[10];
  2678. var trace = m11 + m22 + m33;
  2679. var s;
  2680. if (trace > 0) {
  2681. s = 0.5 / Math.sqrt(trace + 1.0);
  2682. result.w = 0.25 / s;
  2683. result.x = (m32 - m23) * s;
  2684. result.y = (m13 - m31) * s;
  2685. result.z = (m21 - m12) * s;
  2686. }
  2687. else if (m11 > m22 && m11 > m33) {
  2688. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2689. result.w = (m32 - m23) / s;
  2690. result.x = 0.25 * s;
  2691. result.y = (m12 + m21) / s;
  2692. result.z = (m13 + m31) / s;
  2693. }
  2694. else if (m22 > m33) {
  2695. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2696. result.w = (m13 - m31) / s;
  2697. result.x = (m12 + m21) / s;
  2698. result.y = 0.25 * s;
  2699. result.z = (m23 + m32) / s;
  2700. }
  2701. else {
  2702. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2703. result.w = (m21 - m12) / s;
  2704. result.x = (m13 + m31) / s;
  2705. result.y = (m23 + m32) / s;
  2706. result.z = 0.25 * s;
  2707. }
  2708. };
  2709. /**
  2710. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2711. */
  2712. Quaternion.Zero = function () {
  2713. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2714. };
  2715. /**
  2716. * Returns a new Quaternion as the inverted current Quaternion.
  2717. */
  2718. Quaternion.Inverse = function (q) {
  2719. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2720. };
  2721. /**
  2722. * Returns the identity Quaternion.
  2723. */
  2724. Quaternion.Identity = function () {
  2725. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2726. };
  2727. Quaternion.IsIdentity = function (quaternion) {
  2728. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2729. };
  2730. /**
  2731. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2732. */
  2733. Quaternion.RotationAxis = function (axis, angle) {
  2734. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2735. };
  2736. /**
  2737. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2738. */
  2739. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2740. var sin = Math.sin(angle / 2);
  2741. axis.normalize();
  2742. result.w = Math.cos(angle / 2);
  2743. result.x = axis.x * sin;
  2744. result.y = axis.y * sin;
  2745. result.z = axis.z * sin;
  2746. return result;
  2747. };
  2748. /**
  2749. * Retuns a new Quaternion set from the starting index of the passed array.
  2750. */
  2751. Quaternion.FromArray = function (array, offset) {
  2752. if (!offset) {
  2753. offset = 0;
  2754. }
  2755. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2756. };
  2757. /**
  2758. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2759. */
  2760. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2761. var q = new Quaternion();
  2762. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2763. return q;
  2764. };
  2765. /**
  2766. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2767. */
  2768. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2769. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2770. var halfRoll = roll * 0.5;
  2771. var halfPitch = pitch * 0.5;
  2772. var halfYaw = yaw * 0.5;
  2773. var sinRoll = Math.sin(halfRoll);
  2774. var cosRoll = Math.cos(halfRoll);
  2775. var sinPitch = Math.sin(halfPitch);
  2776. var cosPitch = Math.cos(halfPitch);
  2777. var sinYaw = Math.sin(halfYaw);
  2778. var cosYaw = Math.cos(halfYaw);
  2779. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2780. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2781. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2782. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2783. };
  2784. /**
  2785. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2786. */
  2787. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2788. var result = new Quaternion();
  2789. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2790. return result;
  2791. };
  2792. /**
  2793. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2794. */
  2795. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2796. // Produces a quaternion from Euler angles in the z-x-z orientation
  2797. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2798. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2799. var halfBeta = beta * 0.5;
  2800. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2801. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2802. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2803. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2804. };
  2805. /**
  2806. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2807. * cf to Vector3.RotationFromAxis() documentation.
  2808. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2809. */
  2810. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2811. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2812. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2813. return quat;
  2814. };
  2815. /**
  2816. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2817. * cf to Vector3.RotationFromAxis() documentation.
  2818. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2819. */
  2820. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2821. var rotMat = MathTmp.Matrix[0];
  2822. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2823. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2824. };
  2825. Quaternion.Slerp = function (left, right, amount) {
  2826. var result = Quaternion.Identity();
  2827. Quaternion.SlerpToRef(left, right, amount, result);
  2828. return result;
  2829. };
  2830. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2831. var num2;
  2832. var num3;
  2833. var num = amount;
  2834. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2835. var flag = false;
  2836. if (num4 < 0) {
  2837. flag = true;
  2838. num4 = -num4;
  2839. }
  2840. if (num4 > 0.999999) {
  2841. num3 = 1 - num;
  2842. num2 = flag ? -num : num;
  2843. }
  2844. else {
  2845. var num5 = Math.acos(num4);
  2846. var num6 = (1.0 / Math.sin(num5));
  2847. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2848. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2849. }
  2850. result.x = (num3 * left.x) + (num2 * right.x);
  2851. result.y = (num3 * left.y) + (num2 * right.y);
  2852. result.z = (num3 * left.z) + (num2 * right.z);
  2853. result.w = (num3 * left.w) + (num2 * right.w);
  2854. };
  2855. /**
  2856. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2857. */
  2858. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2859. var squared = amount * amount;
  2860. var cubed = amount * squared;
  2861. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2862. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2863. var part3 = (cubed - (2.0 * squared)) + amount;
  2864. var part4 = cubed - squared;
  2865. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2866. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2867. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2868. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2869. return new Quaternion(x, y, z, w);
  2870. };
  2871. return Quaternion;
  2872. }());
  2873. BABYLON.Quaternion = Quaternion;
  2874. var Matrix = /** @class */ (function () {
  2875. function Matrix() {
  2876. this._isIdentity = false;
  2877. this._isIdentityDirty = true;
  2878. this.m = new Float32Array(16);
  2879. this._markAsUpdated();
  2880. }
  2881. Matrix.prototype._markAsUpdated = function () {
  2882. this.updateFlag = Matrix._updateFlagSeed++;
  2883. this._isIdentityDirty = true;
  2884. };
  2885. // Properties
  2886. /**
  2887. * Boolean : True is the matrix is the identity matrix
  2888. */
  2889. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2890. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2891. if (this._isIdentityDirty) {
  2892. this._isIdentityDirty = false;
  2893. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2894. this._isIdentity = false;
  2895. }
  2896. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2897. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2898. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2899. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2900. this._isIdentity = false;
  2901. }
  2902. else {
  2903. this._isIdentity = true;
  2904. }
  2905. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2906. this._isIdentity = false;
  2907. }
  2908. }
  2909. return this._isIdentity;
  2910. };
  2911. /**
  2912. * Returns the matrix determinant (float).
  2913. */
  2914. Matrix.prototype.determinant = function () {
  2915. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2916. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2917. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2918. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2919. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2920. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2921. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2922. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2923. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2924. };
  2925. // Methods
  2926. /**
  2927. * Returns the matrix underlying array.
  2928. */
  2929. Matrix.prototype.toArray = function () {
  2930. return this.m;
  2931. };
  2932. /**
  2933. * Returns the matrix underlying array.
  2934. */
  2935. Matrix.prototype.asArray = function () {
  2936. return this.toArray();
  2937. };
  2938. /**
  2939. * Inverts in place the Matrix.
  2940. * Returns the Matrix inverted.
  2941. */
  2942. Matrix.prototype.invert = function () {
  2943. this.invertToRef(this);
  2944. return this;
  2945. };
  2946. /**
  2947. * Sets all the matrix elements to zero.
  2948. * Returns the Matrix.
  2949. */
  2950. Matrix.prototype.reset = function () {
  2951. for (var index = 0; index < 16; index++) {
  2952. this.m[index] = 0.0;
  2953. }
  2954. this._markAsUpdated();
  2955. return this;
  2956. };
  2957. /**
  2958. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2959. */
  2960. Matrix.prototype.add = function (other) {
  2961. var result = new Matrix();
  2962. this.addToRef(other, result);
  2963. return result;
  2964. };
  2965. /**
  2966. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2967. * Returns the Matrix.
  2968. */
  2969. Matrix.prototype.addToRef = function (other, result) {
  2970. for (var index = 0; index < 16; index++) {
  2971. result.m[index] = this.m[index] + other.m[index];
  2972. }
  2973. result._markAsUpdated();
  2974. return this;
  2975. };
  2976. /**
  2977. * Adds in place the passed matrix to the current Matrix.
  2978. * Returns the updated Matrix.
  2979. */
  2980. Matrix.prototype.addToSelf = function (other) {
  2981. for (var index = 0; index < 16; index++) {
  2982. this.m[index] += other.m[index];
  2983. }
  2984. this._markAsUpdated();
  2985. return this;
  2986. };
  2987. /**
  2988. * Sets the passed matrix with the current inverted Matrix.
  2989. * Returns the unmodified current Matrix.
  2990. */
  2991. Matrix.prototype.invertToRef = function (other) {
  2992. var l1 = this.m[0];
  2993. var l2 = this.m[1];
  2994. var l3 = this.m[2];
  2995. var l4 = this.m[3];
  2996. var l5 = this.m[4];
  2997. var l6 = this.m[5];
  2998. var l7 = this.m[6];
  2999. var l8 = this.m[7];
  3000. var l9 = this.m[8];
  3001. var l10 = this.m[9];
  3002. var l11 = this.m[10];
  3003. var l12 = this.m[11];
  3004. var l13 = this.m[12];
  3005. var l14 = this.m[13];
  3006. var l15 = this.m[14];
  3007. var l16 = this.m[15];
  3008. var l17 = (l11 * l16) - (l12 * l15);
  3009. var l18 = (l10 * l16) - (l12 * l14);
  3010. var l19 = (l10 * l15) - (l11 * l14);
  3011. var l20 = (l9 * l16) - (l12 * l13);
  3012. var l21 = (l9 * l15) - (l11 * l13);
  3013. var l22 = (l9 * l14) - (l10 * l13);
  3014. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3015. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3016. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3017. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3018. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3019. var l28 = (l7 * l16) - (l8 * l15);
  3020. var l29 = (l6 * l16) - (l8 * l14);
  3021. var l30 = (l6 * l15) - (l7 * l14);
  3022. var l31 = (l5 * l16) - (l8 * l13);
  3023. var l32 = (l5 * l15) - (l7 * l13);
  3024. var l33 = (l5 * l14) - (l6 * l13);
  3025. var l34 = (l7 * l12) - (l8 * l11);
  3026. var l35 = (l6 * l12) - (l8 * l10);
  3027. var l36 = (l6 * l11) - (l7 * l10);
  3028. var l37 = (l5 * l12) - (l8 * l9);
  3029. var l38 = (l5 * l11) - (l7 * l9);
  3030. var l39 = (l5 * l10) - (l6 * l9);
  3031. other.m[0] = l23 * l27;
  3032. other.m[4] = l24 * l27;
  3033. other.m[8] = l25 * l27;
  3034. other.m[12] = l26 * l27;
  3035. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3036. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3037. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3038. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3039. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3040. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3041. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3042. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3043. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3044. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3045. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3046. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3047. other._markAsUpdated();
  3048. return this;
  3049. };
  3050. /**
  3051. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3052. * Returns the updated Matrix.
  3053. */
  3054. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3055. this.m[12] = x;
  3056. this.m[13] = y;
  3057. this.m[14] = z;
  3058. this._markAsUpdated();
  3059. return this;
  3060. };
  3061. /**
  3062. * Inserts the translation vector in the current Matrix.
  3063. * Returns the updated Matrix.
  3064. */
  3065. Matrix.prototype.setTranslation = function (vector3) {
  3066. this.m[12] = vector3.x;
  3067. this.m[13] = vector3.y;
  3068. this.m[14] = vector3.z;
  3069. this._markAsUpdated();
  3070. return this;
  3071. };
  3072. /**
  3073. * Returns a new Vector3 as the extracted translation from the Matrix.
  3074. */
  3075. Matrix.prototype.getTranslation = function () {
  3076. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3077. };
  3078. /**
  3079. * Fill a Vector3 with the extracted translation from the Matrix.
  3080. */
  3081. Matrix.prototype.getTranslationToRef = function (result) {
  3082. result.x = this.m[12];
  3083. result.y = this.m[13];
  3084. result.z = this.m[14];
  3085. return this;
  3086. };
  3087. /**
  3088. * Remove rotation and scaling part from the Matrix.
  3089. * Returns the updated Matrix.
  3090. */
  3091. Matrix.prototype.removeRotationAndScaling = function () {
  3092. this.setRowFromFloats(0, 1, 0, 0, 0);
  3093. this.setRowFromFloats(1, 0, 1, 0, 0);
  3094. this.setRowFromFloats(2, 0, 0, 1, 0);
  3095. return this;
  3096. };
  3097. /**
  3098. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3099. */
  3100. Matrix.prototype.multiply = function (other) {
  3101. var result = new Matrix();
  3102. this.multiplyToRef(other, result);
  3103. return result;
  3104. };
  3105. /**
  3106. * Updates the current Matrix from the passed one values.
  3107. * Returns the updated Matrix.
  3108. */
  3109. Matrix.prototype.copyFrom = function (other) {
  3110. for (var index = 0; index < 16; index++) {
  3111. this.m[index] = other.m[index];
  3112. }
  3113. this._markAsUpdated();
  3114. return this;
  3115. };
  3116. /**
  3117. * Populates the passed array from the starting index with the Matrix values.
  3118. * Returns the Matrix.
  3119. */
  3120. Matrix.prototype.copyToArray = function (array, offset) {
  3121. if (offset === void 0) { offset = 0; }
  3122. for (var index = 0; index < 16; index++) {
  3123. array[offset + index] = this.m[index];
  3124. }
  3125. return this;
  3126. };
  3127. /**
  3128. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3129. */
  3130. Matrix.prototype.multiplyToRef = function (other, result) {
  3131. this.multiplyToArray(other, result.m, 0);
  3132. result._markAsUpdated();
  3133. return this;
  3134. };
  3135. /**
  3136. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3137. */
  3138. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3139. var tm0 = this.m[0];
  3140. var tm1 = this.m[1];
  3141. var tm2 = this.m[2];
  3142. var tm3 = this.m[3];
  3143. var tm4 = this.m[4];
  3144. var tm5 = this.m[5];
  3145. var tm6 = this.m[6];
  3146. var tm7 = this.m[7];
  3147. var tm8 = this.m[8];
  3148. var tm9 = this.m[9];
  3149. var tm10 = this.m[10];
  3150. var tm11 = this.m[11];
  3151. var tm12 = this.m[12];
  3152. var tm13 = this.m[13];
  3153. var tm14 = this.m[14];
  3154. var tm15 = this.m[15];
  3155. var om0 = other.m[0];
  3156. var om1 = other.m[1];
  3157. var om2 = other.m[2];
  3158. var om3 = other.m[3];
  3159. var om4 = other.m[4];
  3160. var om5 = other.m[5];
  3161. var om6 = other.m[6];
  3162. var om7 = other.m[7];
  3163. var om8 = other.m[8];
  3164. var om9 = other.m[9];
  3165. var om10 = other.m[10];
  3166. var om11 = other.m[11];
  3167. var om12 = other.m[12];
  3168. var om13 = other.m[13];
  3169. var om14 = other.m[14];
  3170. var om15 = other.m[15];
  3171. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3172. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3173. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3174. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3175. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3176. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3177. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3178. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3179. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3180. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3181. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3182. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3183. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3184. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3185. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3186. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3187. return this;
  3188. };
  3189. /**
  3190. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3191. */
  3192. Matrix.prototype.equals = function (value) {
  3193. return value &&
  3194. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3195. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3196. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3197. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3198. };
  3199. /**
  3200. * Returns a new Matrix from the current Matrix.
  3201. */
  3202. Matrix.prototype.clone = function () {
  3203. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  3204. };
  3205. /**
  3206. * Returns the string "Matrix"
  3207. */
  3208. Matrix.prototype.getClassName = function () {
  3209. return "Matrix";
  3210. };
  3211. /**
  3212. * Returns the Matrix hash code.
  3213. */
  3214. Matrix.prototype.getHashCode = function () {
  3215. var hash = this.m[0] || 0;
  3216. for (var i = 1; i < 16; i++) {
  3217. hash = (hash * 397) ^ (this.m[i] || 0);
  3218. }
  3219. return hash;
  3220. };
  3221. /**
  3222. * Decomposes the current Matrix into :
  3223. * - a scale vector3 passed as a reference to update,
  3224. * - a rotation quaternion passed as a reference to update,
  3225. * - a translation vector3 passed as a reference to update.
  3226. * Returns the boolean `true`.
  3227. */
  3228. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3229. translation.x = this.m[12];
  3230. translation.y = this.m[13];
  3231. translation.z = this.m[14];
  3232. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3233. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3234. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3235. if (this.determinant() <= 0) {
  3236. scale.y *= -1;
  3237. }
  3238. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3239. rotation.x = 0;
  3240. rotation.y = 0;
  3241. rotation.z = 0;
  3242. rotation.w = 1;
  3243. return false;
  3244. }
  3245. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[0]);
  3246. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3247. return true;
  3248. };
  3249. /**
  3250. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3251. */
  3252. Matrix.prototype.getRotationMatrix = function () {
  3253. var result = Matrix.Identity();
  3254. this.getRotationMatrixToRef(result);
  3255. return result;
  3256. };
  3257. /**
  3258. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3259. * Returns the current Matrix.
  3260. */
  3261. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3262. var m = this.m;
  3263. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3264. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3265. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3266. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3267. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3268. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3269. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  3270. return this;
  3271. };
  3272. // Statics
  3273. /**
  3274. * Returns a new Matrix set from the starting index of the passed array.
  3275. */
  3276. Matrix.FromArray = function (array, offset) {
  3277. var result = new Matrix();
  3278. if (!offset) {
  3279. offset = 0;
  3280. }
  3281. Matrix.FromArrayToRef(array, offset, result);
  3282. return result;
  3283. };
  3284. /**
  3285. * Sets the passed "result" matrix from the starting index of the passed array.
  3286. */
  3287. Matrix.FromArrayToRef = function (array, offset, result) {
  3288. for (var index = 0; index < 16; index++) {
  3289. result.m[index] = array[index + offset];
  3290. }
  3291. result._markAsUpdated();
  3292. };
  3293. /**
  3294. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3295. */
  3296. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3297. for (var index = 0; index < 16; index++) {
  3298. result.m[index] = array[index + offset] * scale;
  3299. }
  3300. result._markAsUpdated();
  3301. };
  3302. /**
  3303. * Sets the passed matrix "result" with the 16 passed floats.
  3304. */
  3305. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3306. result.m[0] = initialM11;
  3307. result.m[1] = initialM12;
  3308. result.m[2] = initialM13;
  3309. result.m[3] = initialM14;
  3310. result.m[4] = initialM21;
  3311. result.m[5] = initialM22;
  3312. result.m[6] = initialM23;
  3313. result.m[7] = initialM24;
  3314. result.m[8] = initialM31;
  3315. result.m[9] = initialM32;
  3316. result.m[10] = initialM33;
  3317. result.m[11] = initialM34;
  3318. result.m[12] = initialM41;
  3319. result.m[13] = initialM42;
  3320. result.m[14] = initialM43;
  3321. result.m[15] = initialM44;
  3322. result._markAsUpdated();
  3323. };
  3324. /**
  3325. * Returns the index-th row of the current matrix as a new Vector4.
  3326. */
  3327. Matrix.prototype.getRow = function (index) {
  3328. if (index < 0 || index > 3) {
  3329. return null;
  3330. }
  3331. var i = index * 4;
  3332. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3333. };
  3334. /**
  3335. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3336. * Returns the updated Matrix.
  3337. */
  3338. Matrix.prototype.setRow = function (index, row) {
  3339. if (index < 0 || index > 3) {
  3340. return this;
  3341. }
  3342. var i = index * 4;
  3343. this.m[i + 0] = row.x;
  3344. this.m[i + 1] = row.y;
  3345. this.m[i + 2] = row.z;
  3346. this.m[i + 3] = row.w;
  3347. this._markAsUpdated();
  3348. return this;
  3349. };
  3350. /**
  3351. * Compute the transpose of the matrix.
  3352. * Returns a new Matrix.
  3353. */
  3354. Matrix.prototype.transpose = function () {
  3355. return Matrix.Transpose(this);
  3356. };
  3357. /**
  3358. * Compute the transpose of the matrix.
  3359. * Returns the current matrix.
  3360. */
  3361. Matrix.prototype.transposeToRef = function (result) {
  3362. Matrix.TransposeToRef(this, result);
  3363. return this;
  3364. };
  3365. /**
  3366. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3367. * Returns the updated Matrix.
  3368. */
  3369. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3370. if (index < 0 || index > 3) {
  3371. return this;
  3372. }
  3373. var i = index * 4;
  3374. this.m[i + 0] = x;
  3375. this.m[i + 1] = y;
  3376. this.m[i + 2] = z;
  3377. this.m[i + 3] = w;
  3378. this._markAsUpdated();
  3379. return this;
  3380. };
  3381. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3382. /**
  3383. * Static identity matrix to be used as readonly matrix
  3384. * Must not be updated.
  3385. */
  3386. get: function () {
  3387. return Matrix._identityReadOnly;
  3388. },
  3389. enumerable: true,
  3390. configurable: true
  3391. });
  3392. /**
  3393. * Returns a new Matrix set from the 16 passed floats.
  3394. */
  3395. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3396. var result = new Matrix();
  3397. result.m[0] = initialM11;
  3398. result.m[1] = initialM12;
  3399. result.m[2] = initialM13;
  3400. result.m[3] = initialM14;
  3401. result.m[4] = initialM21;
  3402. result.m[5] = initialM22;
  3403. result.m[6] = initialM23;
  3404. result.m[7] = initialM24;
  3405. result.m[8] = initialM31;
  3406. result.m[9] = initialM32;
  3407. result.m[10] = initialM33;
  3408. result.m[11] = initialM34;
  3409. result.m[12] = initialM41;
  3410. result.m[13] = initialM42;
  3411. result.m[14] = initialM43;
  3412. result.m[15] = initialM44;
  3413. return result;
  3414. };
  3415. /**
  3416. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3417. */
  3418. Matrix.Compose = function (scale, rotation, translation) {
  3419. var result = Matrix.Identity();
  3420. Matrix.ComposeToRef(scale, rotation, translation, result);
  3421. return result;
  3422. };
  3423. /**
  3424. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3425. */
  3426. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3427. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3428. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3429. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3430. result.setTranslation(translation);
  3431. };
  3432. /**
  3433. * Returns a new indentity Matrix.
  3434. */
  3435. Matrix.Identity = function () {
  3436. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3437. };
  3438. /**
  3439. * Sets the passed "result" as an identity matrix.
  3440. */
  3441. Matrix.IdentityToRef = function (result) {
  3442. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3443. };
  3444. /**
  3445. * Returns a new zero Matrix.
  3446. */
  3447. Matrix.Zero = function () {
  3448. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3449. };
  3450. /**
  3451. * Returns a new rotation matrix for "angle" radians around the X axis.
  3452. */
  3453. Matrix.RotationX = function (angle) {
  3454. var result = new Matrix();
  3455. Matrix.RotationXToRef(angle, result);
  3456. return result;
  3457. };
  3458. /**
  3459. * Returns a new Matrix as the passed inverted one.
  3460. */
  3461. Matrix.Invert = function (source) {
  3462. var result = new Matrix();
  3463. source.invertToRef(result);
  3464. return result;
  3465. };
  3466. /**
  3467. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3468. */
  3469. Matrix.RotationXToRef = function (angle, result) {
  3470. var s = Math.sin(angle);
  3471. var c = Math.cos(angle);
  3472. result.m[0] = 1.0;
  3473. result.m[15] = 1.0;
  3474. result.m[5] = c;
  3475. result.m[10] = c;
  3476. result.m[9] = -s;
  3477. result.m[6] = s;
  3478. result.m[1] = 0.0;
  3479. result.m[2] = 0.0;
  3480. result.m[3] = 0.0;
  3481. result.m[4] = 0.0;
  3482. result.m[7] = 0.0;
  3483. result.m[8] = 0.0;
  3484. result.m[11] = 0.0;
  3485. result.m[12] = 0.0;
  3486. result.m[13] = 0.0;
  3487. result.m[14] = 0.0;
  3488. result._markAsUpdated();
  3489. };
  3490. /**
  3491. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3492. */
  3493. Matrix.RotationY = function (angle) {
  3494. var result = new Matrix();
  3495. Matrix.RotationYToRef(angle, result);
  3496. return result;
  3497. };
  3498. /**
  3499. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3500. */
  3501. Matrix.RotationYToRef = function (angle, result) {
  3502. var s = Math.sin(angle);
  3503. var c = Math.cos(angle);
  3504. result.m[5] = 1.0;
  3505. result.m[15] = 1.0;
  3506. result.m[0] = c;
  3507. result.m[2] = -s;
  3508. result.m[8] = s;
  3509. result.m[10] = c;
  3510. result.m[1] = 0.0;
  3511. result.m[3] = 0.0;
  3512. result.m[4] = 0.0;
  3513. result.m[6] = 0.0;
  3514. result.m[7] = 0.0;
  3515. result.m[9] = 0.0;
  3516. result.m[11] = 0.0;
  3517. result.m[12] = 0.0;
  3518. result.m[13] = 0.0;
  3519. result.m[14] = 0.0;
  3520. result._markAsUpdated();
  3521. };
  3522. /**
  3523. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3524. */
  3525. Matrix.RotationZ = function (angle) {
  3526. var result = new Matrix();
  3527. Matrix.RotationZToRef(angle, result);
  3528. return result;
  3529. };
  3530. /**
  3531. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3532. */
  3533. Matrix.RotationZToRef = function (angle, result) {
  3534. var s = Math.sin(angle);
  3535. var c = Math.cos(angle);
  3536. result.m[10] = 1.0;
  3537. result.m[15] = 1.0;
  3538. result.m[0] = c;
  3539. result.m[1] = s;
  3540. result.m[4] = -s;
  3541. result.m[5] = c;
  3542. result.m[2] = 0.0;
  3543. result.m[3] = 0.0;
  3544. result.m[6] = 0.0;
  3545. result.m[7] = 0.0;
  3546. result.m[8] = 0.0;
  3547. result.m[9] = 0.0;
  3548. result.m[11] = 0.0;
  3549. result.m[12] = 0.0;
  3550. result.m[13] = 0.0;
  3551. result.m[14] = 0.0;
  3552. result._markAsUpdated();
  3553. };
  3554. /**
  3555. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3556. */
  3557. Matrix.RotationAxis = function (axis, angle) {
  3558. var result = Matrix.Zero();
  3559. Matrix.RotationAxisToRef(axis, angle, result);
  3560. return result;
  3561. };
  3562. /**
  3563. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3564. */
  3565. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3566. var s = Math.sin(-angle);
  3567. var c = Math.cos(-angle);
  3568. var c1 = 1 - c;
  3569. axis.normalize();
  3570. result.m[0] = (axis.x * axis.x) * c1 + c;
  3571. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3572. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3573. result.m[3] = 0.0;
  3574. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3575. result.m[5] = (axis.y * axis.y) * c1 + c;
  3576. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3577. result.m[7] = 0.0;
  3578. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3579. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3580. result.m[10] = (axis.z * axis.z) * c1 + c;
  3581. result.m[11] = 0.0;
  3582. result.m[15] = 1.0;
  3583. result._markAsUpdated();
  3584. };
  3585. /**
  3586. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3587. */
  3588. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3589. var result = new Matrix();
  3590. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3591. return result;
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3595. */
  3596. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3597. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3598. this._tempQuaternion.toRotationMatrix(result);
  3599. };
  3600. /**
  3601. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3602. */
  3603. Matrix.Scaling = function (x, y, z) {
  3604. var result = Matrix.Zero();
  3605. Matrix.ScalingToRef(x, y, z, result);
  3606. return result;
  3607. };
  3608. /**
  3609. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3610. */
  3611. Matrix.ScalingToRef = function (x, y, z, result) {
  3612. result.m[0] = x;
  3613. result.m[1] = 0.0;
  3614. result.m[2] = 0.0;
  3615. result.m[3] = 0.0;
  3616. result.m[4] = 0.0;
  3617. result.m[5] = y;
  3618. result.m[6] = 0.0;
  3619. result.m[7] = 0.0;
  3620. result.m[8] = 0.0;
  3621. result.m[9] = 0.0;
  3622. result.m[10] = z;
  3623. result.m[11] = 0.0;
  3624. result.m[12] = 0.0;
  3625. result.m[13] = 0.0;
  3626. result.m[14] = 0.0;
  3627. result.m[15] = 1.0;
  3628. result._markAsUpdated();
  3629. };
  3630. /**
  3631. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3632. */
  3633. Matrix.Translation = function (x, y, z) {
  3634. var result = Matrix.Identity();
  3635. Matrix.TranslationToRef(x, y, z, result);
  3636. return result;
  3637. };
  3638. /**
  3639. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3640. */
  3641. Matrix.TranslationToRef = function (x, y, z, result) {
  3642. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3643. };
  3644. /**
  3645. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3646. */
  3647. Matrix.Lerp = function (startValue, endValue, gradient) {
  3648. var result = Matrix.Zero();
  3649. for (var index = 0; index < 16; index++) {
  3650. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3651. }
  3652. result._markAsUpdated();
  3653. return result;
  3654. };
  3655. /**
  3656. * Returns a new Matrix whose values are computed by :
  3657. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3658. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3659. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3660. */
  3661. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3662. var startScale = new Vector3(0, 0, 0);
  3663. var startRotation = new Quaternion();
  3664. var startTranslation = new Vector3(0, 0, 0);
  3665. startValue.decompose(startScale, startRotation, startTranslation);
  3666. var endScale = new Vector3(0, 0, 0);
  3667. var endRotation = new Quaternion();
  3668. var endTranslation = new Vector3(0, 0, 0);
  3669. endValue.decompose(endScale, endRotation, endTranslation);
  3670. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3671. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3672. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3673. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3674. };
  3675. /**
  3676. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3677. * This methods works for a Left-Handed system.
  3678. */
  3679. Matrix.LookAtLH = function (eye, target, up) {
  3680. var result = Matrix.Zero();
  3681. Matrix.LookAtLHToRef(eye, target, up, result);
  3682. return result;
  3683. };
  3684. /**
  3685. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3686. * This methods works for a Left-Handed system.
  3687. */
  3688. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3689. // Z axis
  3690. target.subtractToRef(eye, this._zAxis);
  3691. this._zAxis.normalize();
  3692. // X axis
  3693. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3694. if (this._xAxis.lengthSquared() === 0) {
  3695. this._xAxis.x = 1.0;
  3696. }
  3697. else {
  3698. this._xAxis.normalize();
  3699. }
  3700. // Y axis
  3701. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3702. this._yAxis.normalize();
  3703. // Eye angles
  3704. var ex = -Vector3.Dot(this._xAxis, eye);
  3705. var ey = -Vector3.Dot(this._yAxis, eye);
  3706. var ez = -Vector3.Dot(this._zAxis, eye);
  3707. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3708. };
  3709. /**
  3710. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3711. * This methods works for a Right-Handed system.
  3712. */
  3713. Matrix.LookAtRH = function (eye, target, up) {
  3714. var result = Matrix.Zero();
  3715. Matrix.LookAtRHToRef(eye, target, up, result);
  3716. return result;
  3717. };
  3718. /**
  3719. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3720. * This methods works for a Left-Handed system.
  3721. */
  3722. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3723. // Z axis
  3724. eye.subtractToRef(target, this._zAxis);
  3725. this._zAxis.normalize();
  3726. // X axis
  3727. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3728. if (this._xAxis.lengthSquared() === 0) {
  3729. this._xAxis.x = 1.0;
  3730. }
  3731. else {
  3732. this._xAxis.normalize();
  3733. }
  3734. // Y axis
  3735. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3736. this._yAxis.normalize();
  3737. // Eye angles
  3738. var ex = -Vector3.Dot(this._xAxis, eye);
  3739. var ey = -Vector3.Dot(this._yAxis, eye);
  3740. var ez = -Vector3.Dot(this._zAxis, eye);
  3741. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  3742. };
  3743. /**
  3744. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3745. */
  3746. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3747. var matrix = Matrix.Zero();
  3748. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3749. return matrix;
  3750. };
  3751. /**
  3752. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3753. */
  3754. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3755. var n = znear;
  3756. var f = zfar;
  3757. var a = 2.0 / width;
  3758. var b = 2.0 / height;
  3759. var c = 2.0 / (f - n);
  3760. var d = -(f + n) / (f - n);
  3761. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3762. };
  3763. /**
  3764. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3765. */
  3766. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3767. var matrix = Matrix.Zero();
  3768. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3769. return matrix;
  3770. };
  3771. /**
  3772. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3773. */
  3774. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3775. var n = znear;
  3776. var f = zfar;
  3777. var a = 2.0 / (right - left);
  3778. var b = 2.0 / (top - bottom);
  3779. var c = 2.0 / (f - n);
  3780. var d = -(f + n) / (f - n);
  3781. var i0 = (left + right) / (left - right);
  3782. var i1 = (top + bottom) / (bottom - top);
  3783. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3784. };
  3785. /**
  3786. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3787. */
  3788. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3789. var matrix = Matrix.Zero();
  3790. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3791. return matrix;
  3792. };
  3793. /**
  3794. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3795. */
  3796. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3797. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3798. result.m[10] *= -1.0;
  3799. };
  3800. /**
  3801. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3802. */
  3803. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3804. var matrix = Matrix.Zero();
  3805. var n = znear;
  3806. var f = zfar;
  3807. var a = 2.0 * n / width;
  3808. var b = 2.0 * n / height;
  3809. var c = (f + n) / (f - n);
  3810. var d = -2.0 * f * n / (f - n);
  3811. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3812. return matrix;
  3813. };
  3814. /**
  3815. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3816. */
  3817. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3818. var matrix = Matrix.Zero();
  3819. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3820. return matrix;
  3821. };
  3822. /**
  3823. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3824. */
  3825. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3826. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3827. var n = znear;
  3828. var f = zfar;
  3829. var t = 1.0 / (Math.tan(fov * 0.5));
  3830. var a = isVerticalFovFixed ? (t / aspect) : t;
  3831. var b = isVerticalFovFixed ? t : (t * aspect);
  3832. var c = (f + n) / (f - n);
  3833. var d = -2.0 * f * n / (f - n);
  3834. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3835. };
  3836. /**
  3837. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3838. */
  3839. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3840. var matrix = Matrix.Zero();
  3841. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3842. return matrix;
  3843. };
  3844. /**
  3845. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3846. */
  3847. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3848. //alternatively this could be expressed as:
  3849. // m = PerspectiveFovLHToRef
  3850. // m[10] *= -1.0;
  3851. // m[11] *= -1.0;
  3852. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3853. var n = znear;
  3854. var f = zfar;
  3855. var t = 1.0 / (Math.tan(fov * 0.5));
  3856. var a = isVerticalFovFixed ? (t / aspect) : t;
  3857. var b = isVerticalFovFixed ? t : (t * aspect);
  3858. var c = -(f + n) / (f - n);
  3859. var d = -2 * f * n / (f - n);
  3860. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3861. };
  3862. /**
  3863. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3864. */
  3865. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3866. if (rightHanded === void 0) { rightHanded = false; }
  3867. var rightHandedFactor = rightHanded ? -1 : 1;
  3868. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3869. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3870. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3871. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3872. var xScale = 2.0 / (leftTan + rightTan);
  3873. var yScale = 2.0 / (upTan + downTan);
  3874. result.m[0] = xScale;
  3875. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3876. result.m[5] = yScale;
  3877. result.m[6] = result.m[7] = 0.0;
  3878. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3879. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3880. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3881. result.m[10] = -zfar / (znear - zfar);
  3882. result.m[11] = 1.0 * rightHandedFactor;
  3883. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3884. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3885. // result.m[14] = (znear * zfar) / (znear - zfar);
  3886. result._markAsUpdated();
  3887. };
  3888. /**
  3889. * Returns the final transformation matrix : world * view * projection * viewport
  3890. */
  3891. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3892. var cw = viewport.width;
  3893. var ch = viewport.height;
  3894. var cx = viewport.x;
  3895. var cy = viewport.y;
  3896. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3897. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3898. };
  3899. /**
  3900. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3901. */
  3902. Matrix.GetAsMatrix2x2 = function (matrix) {
  3903. return new Float32Array([
  3904. matrix.m[0], matrix.m[1],
  3905. matrix.m[4], matrix.m[5]
  3906. ]);
  3907. };
  3908. /**
  3909. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3910. */
  3911. Matrix.GetAsMatrix3x3 = function (matrix) {
  3912. return new Float32Array([
  3913. matrix.m[0], matrix.m[1], matrix.m[2],
  3914. matrix.m[4], matrix.m[5], matrix.m[6],
  3915. matrix.m[8], matrix.m[9], matrix.m[10]
  3916. ]);
  3917. };
  3918. /**
  3919. * Compute the transpose of the passed Matrix.
  3920. * Returns a new Matrix.
  3921. */
  3922. Matrix.Transpose = function (matrix) {
  3923. var result = new Matrix();
  3924. Matrix.TransposeToRef(matrix, result);
  3925. return result;
  3926. };
  3927. /**
  3928. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3929. */
  3930. Matrix.TransposeToRef = function (matrix, result) {
  3931. result.m[0] = matrix.m[0];
  3932. result.m[1] = matrix.m[4];
  3933. result.m[2] = matrix.m[8];
  3934. result.m[3] = matrix.m[12];
  3935. result.m[4] = matrix.m[1];
  3936. result.m[5] = matrix.m[5];
  3937. result.m[6] = matrix.m[9];
  3938. result.m[7] = matrix.m[13];
  3939. result.m[8] = matrix.m[2];
  3940. result.m[9] = matrix.m[6];
  3941. result.m[10] = matrix.m[10];
  3942. result.m[11] = matrix.m[14];
  3943. result.m[12] = matrix.m[3];
  3944. result.m[13] = matrix.m[7];
  3945. result.m[14] = matrix.m[11];
  3946. result.m[15] = matrix.m[15];
  3947. };
  3948. /**
  3949. * Returns a new Matrix as the reflection matrix across the passed plane.
  3950. */
  3951. Matrix.Reflection = function (plane) {
  3952. var matrix = new Matrix();
  3953. Matrix.ReflectionToRef(plane, matrix);
  3954. return matrix;
  3955. };
  3956. /**
  3957. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3958. */
  3959. Matrix.ReflectionToRef = function (plane, result) {
  3960. plane.normalize();
  3961. var x = plane.normal.x;
  3962. var y = plane.normal.y;
  3963. var z = plane.normal.z;
  3964. var temp = -2 * x;
  3965. var temp2 = -2 * y;
  3966. var temp3 = -2 * z;
  3967. result.m[0] = (temp * x) + 1;
  3968. result.m[1] = temp2 * x;
  3969. result.m[2] = temp3 * x;
  3970. result.m[3] = 0.0;
  3971. result.m[4] = temp * y;
  3972. result.m[5] = (temp2 * y) + 1;
  3973. result.m[6] = temp3 * y;
  3974. result.m[7] = 0.0;
  3975. result.m[8] = temp * z;
  3976. result.m[9] = temp2 * z;
  3977. result.m[10] = (temp3 * z) + 1;
  3978. result.m[11] = 0.0;
  3979. result.m[12] = temp * plane.d;
  3980. result.m[13] = temp2 * plane.d;
  3981. result.m[14] = temp3 * plane.d;
  3982. result.m[15] = 1.0;
  3983. result._markAsUpdated();
  3984. };
  3985. /**
  3986. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3987. */
  3988. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3989. result.m[0] = xaxis.x;
  3990. result.m[1] = xaxis.y;
  3991. result.m[2] = xaxis.z;
  3992. result.m[3] = 0.0;
  3993. result.m[4] = yaxis.x;
  3994. result.m[5] = yaxis.y;
  3995. result.m[6] = yaxis.z;
  3996. result.m[7] = 0.0;
  3997. result.m[8] = zaxis.x;
  3998. result.m[9] = zaxis.y;
  3999. result.m[10] = zaxis.z;
  4000. result.m[11] = 0.0;
  4001. result.m[12] = 0.0;
  4002. result.m[13] = 0.0;
  4003. result.m[14] = 0.0;
  4004. result.m[15] = 1.0;
  4005. result._markAsUpdated();
  4006. };
  4007. /**
  4008. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4009. */
  4010. Matrix.FromQuaternionToRef = function (quat, result) {
  4011. var xx = quat.x * quat.x;
  4012. var yy = quat.y * quat.y;
  4013. var zz = quat.z * quat.z;
  4014. var xy = quat.x * quat.y;
  4015. var zw = quat.z * quat.w;
  4016. var zx = quat.z * quat.x;
  4017. var yw = quat.y * quat.w;
  4018. var yz = quat.y * quat.z;
  4019. var xw = quat.x * quat.w;
  4020. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4021. result.m[1] = 2.0 * (xy + zw);
  4022. result.m[2] = 2.0 * (zx - yw);
  4023. result.m[3] = 0.0;
  4024. result.m[4] = 2.0 * (xy - zw);
  4025. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4026. result.m[6] = 2.0 * (yz + xw);
  4027. result.m[7] = 0.0;
  4028. result.m[8] = 2.0 * (zx + yw);
  4029. result.m[9] = 2.0 * (yz - xw);
  4030. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4031. result.m[11] = 0.0;
  4032. result.m[12] = 0.0;
  4033. result.m[13] = 0.0;
  4034. result.m[14] = 0.0;
  4035. result.m[15] = 1.0;
  4036. result._markAsUpdated();
  4037. };
  4038. Matrix._tempQuaternion = new Quaternion();
  4039. Matrix._xAxis = Vector3.Zero();
  4040. Matrix._yAxis = Vector3.Zero();
  4041. Matrix._zAxis = Vector3.Zero();
  4042. Matrix._updateFlagSeed = 0;
  4043. Matrix._identityReadOnly = Matrix.Identity();
  4044. return Matrix;
  4045. }());
  4046. BABYLON.Matrix = Matrix;
  4047. var Plane = /** @class */ (function () {
  4048. /**
  4049. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4050. */
  4051. function Plane(a, b, c, d) {
  4052. this.normal = new Vector3(a, b, c);
  4053. this.d = d;
  4054. }
  4055. /**
  4056. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4057. */
  4058. Plane.prototype.asArray = function () {
  4059. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4060. };
  4061. // Methods
  4062. /**
  4063. * Returns a new plane copied from the current Plane.
  4064. */
  4065. Plane.prototype.clone = function () {
  4066. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4067. };
  4068. /**
  4069. * Returns the string "Plane".
  4070. */
  4071. Plane.prototype.getClassName = function () {
  4072. return "Plane";
  4073. };
  4074. /**
  4075. * Returns the Plane hash code.
  4076. */
  4077. Plane.prototype.getHashCode = function () {
  4078. var hash = this.normal.getHashCode();
  4079. hash = (hash * 397) ^ (this.d || 0);
  4080. return hash;
  4081. };
  4082. /**
  4083. * Normalize the current Plane in place.
  4084. * Returns the updated Plane.
  4085. */
  4086. Plane.prototype.normalize = function () {
  4087. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4088. var magnitude = 0.0;
  4089. if (norm !== 0) {
  4090. magnitude = 1.0 / norm;
  4091. }
  4092. this.normal.x *= magnitude;
  4093. this.normal.y *= magnitude;
  4094. this.normal.z *= magnitude;
  4095. this.d *= magnitude;
  4096. return this;
  4097. };
  4098. /**
  4099. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4100. */
  4101. Plane.prototype.transform = function (transformation) {
  4102. var transposedMatrix = Matrix.Transpose(transformation);
  4103. var x = this.normal.x;
  4104. var y = this.normal.y;
  4105. var z = this.normal.z;
  4106. var d = this.d;
  4107. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4108. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4109. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4110. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4111. return new Plane(normalX, normalY, normalZ, finalD);
  4112. };
  4113. /**
  4114. * Returns the dot product (float) of the point coordinates and the plane normal.
  4115. */
  4116. Plane.prototype.dotCoordinate = function (point) {
  4117. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4118. };
  4119. /**
  4120. * Updates the current Plane from the plane defined by the three passed points.
  4121. * Returns the updated Plane.
  4122. */
  4123. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4124. var x1 = point2.x - point1.x;
  4125. var y1 = point2.y - point1.y;
  4126. var z1 = point2.z - point1.z;
  4127. var x2 = point3.x - point1.x;
  4128. var y2 = point3.y - point1.y;
  4129. var z2 = point3.z - point1.z;
  4130. var yz = (y1 * z2) - (z1 * y2);
  4131. var xz = (z1 * x2) - (x1 * z2);
  4132. var xy = (x1 * y2) - (y1 * x2);
  4133. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4134. var invPyth;
  4135. if (pyth !== 0) {
  4136. invPyth = 1.0 / pyth;
  4137. }
  4138. else {
  4139. invPyth = 0.0;
  4140. }
  4141. this.normal.x = yz * invPyth;
  4142. this.normal.y = xz * invPyth;
  4143. this.normal.z = xy * invPyth;
  4144. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4145. return this;
  4146. };
  4147. /**
  4148. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4149. */
  4150. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4151. var dot = Vector3.Dot(this.normal, direction);
  4152. return (dot <= epsilon);
  4153. };
  4154. /**
  4155. * Returns the signed distance (float) from the passed point to the Plane.
  4156. */
  4157. Plane.prototype.signedDistanceTo = function (point) {
  4158. return Vector3.Dot(point, this.normal) + this.d;
  4159. };
  4160. // Statics
  4161. /**
  4162. * Returns a new Plane from the passed array.
  4163. */
  4164. Plane.FromArray = function (array) {
  4165. return new Plane(array[0], array[1], array[2], array[3]);
  4166. };
  4167. /**
  4168. * Returns a new Plane defined by the three passed points.
  4169. */
  4170. Plane.FromPoints = function (point1, point2, point3) {
  4171. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4172. result.copyFromPoints(point1, point2, point3);
  4173. return result;
  4174. };
  4175. /**
  4176. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4177. * Note : the vector "normal" is updated because normalized.
  4178. */
  4179. Plane.FromPositionAndNormal = function (origin, normal) {
  4180. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4181. normal.normalize();
  4182. result.normal = normal;
  4183. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4184. return result;
  4185. };
  4186. /**
  4187. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4188. */
  4189. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4190. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4191. return Vector3.Dot(point, normal) + d;
  4192. };
  4193. return Plane;
  4194. }());
  4195. BABYLON.Plane = Plane;
  4196. var Viewport = /** @class */ (function () {
  4197. /**
  4198. * Creates a Viewport object located at (x, y) and sized (width, height).
  4199. */
  4200. function Viewport(x, y, width, height) {
  4201. this.x = x;
  4202. this.y = y;
  4203. this.width = width;
  4204. this.height = height;
  4205. }
  4206. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4207. if (renderWidthOrEngine.getRenderWidth) {
  4208. var engine = renderWidthOrEngine;
  4209. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4210. }
  4211. var renderWidth = renderWidthOrEngine;
  4212. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4213. };
  4214. /**
  4215. * Returns a new Viewport copied from the current one.
  4216. */
  4217. Viewport.prototype.clone = function () {
  4218. return new Viewport(this.x, this.y, this.width, this.height);
  4219. };
  4220. return Viewport;
  4221. }());
  4222. BABYLON.Viewport = Viewport;
  4223. var Frustum = /** @class */ (function () {
  4224. function Frustum() {
  4225. }
  4226. /**
  4227. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4228. */
  4229. Frustum.GetPlanes = function (transform) {
  4230. var frustumPlanes = [];
  4231. for (var index = 0; index < 6; index++) {
  4232. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4233. }
  4234. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4235. return frustumPlanes;
  4236. };
  4237. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4238. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4239. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4240. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4241. frustumPlane.d = transform.m[15] + transform.m[14];
  4242. frustumPlane.normalize();
  4243. };
  4244. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4245. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4246. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4247. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4248. frustumPlane.d = transform.m[15] - transform.m[14];
  4249. frustumPlane.normalize();
  4250. };
  4251. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4252. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4253. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4254. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4255. frustumPlane.d = transform.m[15] + transform.m[12];
  4256. frustumPlane.normalize();
  4257. };
  4258. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4259. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4260. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4261. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4262. frustumPlane.d = transform.m[15] - transform.m[12];
  4263. frustumPlane.normalize();
  4264. };
  4265. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4266. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4267. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4268. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4269. frustumPlane.d = transform.m[15] - transform.m[13];
  4270. frustumPlane.normalize();
  4271. };
  4272. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4273. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4274. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4275. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4276. frustumPlane.d = transform.m[15] + transform.m[13];
  4277. frustumPlane.normalize();
  4278. };
  4279. /**
  4280. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4281. */
  4282. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4283. // Near
  4284. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4285. // Far
  4286. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4287. // Left
  4288. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4289. // Right
  4290. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4291. // Top
  4292. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4293. // Bottom
  4294. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4295. };
  4296. return Frustum;
  4297. }());
  4298. BABYLON.Frustum = Frustum;
  4299. var Space;
  4300. (function (Space) {
  4301. Space[Space["LOCAL"] = 0] = "LOCAL";
  4302. Space[Space["WORLD"] = 1] = "WORLD";
  4303. Space[Space["BONE"] = 2] = "BONE";
  4304. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4305. var Axis = /** @class */ (function () {
  4306. function Axis() {
  4307. }
  4308. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4309. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4310. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4311. return Axis;
  4312. }());
  4313. BABYLON.Axis = Axis;
  4314. ;
  4315. var BezierCurve = /** @class */ (function () {
  4316. function BezierCurve() {
  4317. }
  4318. /**
  4319. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4320. */
  4321. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4322. // Extract X (which is equal to time here)
  4323. var f0 = 1 - 3 * x2 + 3 * x1;
  4324. var f1 = 3 * x2 - 6 * x1;
  4325. var f2 = 3 * x1;
  4326. var refinedT = t;
  4327. for (var i = 0; i < 5; i++) {
  4328. var refinedT2 = refinedT * refinedT;
  4329. var refinedT3 = refinedT2 * refinedT;
  4330. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4331. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4332. refinedT -= (x - t) * slope;
  4333. refinedT = Math.min(1, Math.max(0, refinedT));
  4334. }
  4335. // Resolve cubic bezier for the given x
  4336. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4337. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4338. Math.pow(refinedT, 3);
  4339. };
  4340. return BezierCurve;
  4341. }());
  4342. BABYLON.BezierCurve = BezierCurve;
  4343. var Orientation;
  4344. (function (Orientation) {
  4345. Orientation[Orientation["CW"] = 0] = "CW";
  4346. Orientation[Orientation["CCW"] = 1] = "CCW";
  4347. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4348. var Angle = /** @class */ (function () {
  4349. /**
  4350. * Creates an Angle object of "radians" radians (float).
  4351. */
  4352. function Angle(radians) {
  4353. var _this = this;
  4354. /**
  4355. * Returns the Angle value in degrees (float).
  4356. */
  4357. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4358. /**
  4359. * Returns the Angle value in radians (float).
  4360. */
  4361. this.radians = function () { return _this._radians; };
  4362. this._radians = radians;
  4363. if (this._radians < 0.0)
  4364. this._radians += (2.0 * Math.PI);
  4365. }
  4366. /**
  4367. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4368. */
  4369. Angle.BetweenTwoPoints = function (a, b) {
  4370. var delta = b.subtract(a);
  4371. var theta = Math.atan2(delta.y, delta.x);
  4372. return new Angle(theta);
  4373. };
  4374. /**
  4375. * Returns a new Angle object from the passed float in radians.
  4376. */
  4377. Angle.FromRadians = function (radians) {
  4378. return new Angle(radians);
  4379. };
  4380. /**
  4381. * Returns a new Angle object from the passed float in degrees.
  4382. */
  4383. Angle.FromDegrees = function (degrees) {
  4384. return new Angle(degrees * Math.PI / 180.0);
  4385. };
  4386. return Angle;
  4387. }());
  4388. BABYLON.Angle = Angle;
  4389. var Arc2 = /** @class */ (function () {
  4390. /**
  4391. * Creates an Arc object from the three passed points : start, middle and end.
  4392. */
  4393. function Arc2(startPoint, midPoint, endPoint) {
  4394. this.startPoint = startPoint;
  4395. this.midPoint = midPoint;
  4396. this.endPoint = endPoint;
  4397. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4398. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4399. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4400. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4401. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  4402. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4403. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4404. var a1 = this.startAngle.degrees();
  4405. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4406. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4407. // angles correction
  4408. if (a2 - a1 > +180.0)
  4409. a2 -= 360.0;
  4410. if (a2 - a1 < -180.0)
  4411. a2 += 360.0;
  4412. if (a3 - a2 > +180.0)
  4413. a3 -= 360.0;
  4414. if (a3 - a2 < -180.0)
  4415. a3 += 360.0;
  4416. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4417. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4418. }
  4419. return Arc2;
  4420. }());
  4421. BABYLON.Arc2 = Arc2;
  4422. var Path2 = /** @class */ (function () {
  4423. /**
  4424. * Creates a Path2 object from the starting 2D coordinates x and y.
  4425. */
  4426. function Path2(x, y) {
  4427. this._points = new Array();
  4428. this._length = 0.0;
  4429. this.closed = false;
  4430. this._points.push(new Vector2(x, y));
  4431. }
  4432. /**
  4433. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4434. * Returns the updated Path2.
  4435. */
  4436. Path2.prototype.addLineTo = function (x, y) {
  4437. if (closed) {
  4438. //Tools.Error("cannot add lines to closed paths");
  4439. return this;
  4440. }
  4441. var newPoint = new Vector2(x, y);
  4442. var previousPoint = this._points[this._points.length - 1];
  4443. this._points.push(newPoint);
  4444. this._length += newPoint.subtract(previousPoint).length();
  4445. return this;
  4446. };
  4447. /**
  4448. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4449. * Returns the updated Path2.
  4450. */
  4451. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4452. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4453. if (closed) {
  4454. //Tools.Error("cannot add arcs to closed paths");
  4455. return this;
  4456. }
  4457. var startPoint = this._points[this._points.length - 1];
  4458. var midPoint = new Vector2(midX, midY);
  4459. var endPoint = new Vector2(endX, endY);
  4460. var arc = new Arc2(startPoint, midPoint, endPoint);
  4461. var increment = arc.angle.radians() / numberOfSegments;
  4462. if (arc.orientation === Orientation.CW)
  4463. increment *= -1;
  4464. var currentAngle = arc.startAngle.radians() + increment;
  4465. for (var i = 0; i < numberOfSegments; i++) {
  4466. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4467. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4468. this.addLineTo(x, y);
  4469. currentAngle += increment;
  4470. }
  4471. return this;
  4472. };
  4473. /**
  4474. * Closes the Path2.
  4475. * Returns the Path2.
  4476. */
  4477. Path2.prototype.close = function () {
  4478. this.closed = true;
  4479. return this;
  4480. };
  4481. /**
  4482. * Returns the Path2 total length (float).
  4483. */
  4484. Path2.prototype.length = function () {
  4485. var result = this._length;
  4486. if (!this.closed) {
  4487. var lastPoint = this._points[this._points.length - 1];
  4488. var firstPoint = this._points[0];
  4489. result += (firstPoint.subtract(lastPoint).length());
  4490. }
  4491. return result;
  4492. };
  4493. /**
  4494. * Returns the Path2 internal array of points.
  4495. */
  4496. Path2.prototype.getPoints = function () {
  4497. return this._points;
  4498. };
  4499. /**
  4500. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4501. */
  4502. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4503. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4504. //Tools.Error("normalized length position should be between 0 and 1.");
  4505. return Vector2.Zero();
  4506. }
  4507. var lengthPosition = normalizedLengthPosition * this.length();
  4508. var previousOffset = 0;
  4509. for (var i = 0; i < this._points.length; i++) {
  4510. var j = (i + 1) % this._points.length;
  4511. var a = this._points[i];
  4512. var b = this._points[j];
  4513. var bToA = b.subtract(a);
  4514. var nextOffset = (bToA.length() + previousOffset);
  4515. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4516. var dir = bToA.normalize();
  4517. var localOffset = lengthPosition - previousOffset;
  4518. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4519. }
  4520. previousOffset = nextOffset;
  4521. }
  4522. //Tools.Error("internal error");
  4523. return Vector2.Zero();
  4524. };
  4525. /**
  4526. * Returns a new Path2 starting at the coordinates (x, y).
  4527. */
  4528. Path2.StartingAt = function (x, y) {
  4529. return new Path2(x, y);
  4530. };
  4531. return Path2;
  4532. }());
  4533. BABYLON.Path2 = Path2;
  4534. var Path3D = /** @class */ (function () {
  4535. /**
  4536. * new Path3D(path, normal, raw)
  4537. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4538. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4539. * path : an array of Vector3, the curve axis of the Path3D
  4540. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4541. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4542. */
  4543. function Path3D(path, firstNormal, raw) {
  4544. if (firstNormal === void 0) { firstNormal = null; }
  4545. this.path = path;
  4546. this._curve = new Array();
  4547. this._distances = new Array();
  4548. this._tangents = new Array();
  4549. this._normals = new Array();
  4550. this._binormals = new Array();
  4551. for (var p = 0; p < path.length; p++) {
  4552. this._curve[p] = path[p].clone(); // hard copy
  4553. }
  4554. this._raw = raw || false;
  4555. this._compute(firstNormal);
  4556. }
  4557. /**
  4558. * Returns the Path3D array of successive Vector3 designing its curve.
  4559. */
  4560. Path3D.prototype.getCurve = function () {
  4561. return this._curve;
  4562. };
  4563. /**
  4564. * Returns an array populated with tangent vectors on each Path3D curve point.
  4565. */
  4566. Path3D.prototype.getTangents = function () {
  4567. return this._tangents;
  4568. };
  4569. /**
  4570. * Returns an array populated with normal vectors on each Path3D curve point.
  4571. */
  4572. Path3D.prototype.getNormals = function () {
  4573. return this._normals;
  4574. };
  4575. /**
  4576. * Returns an array populated with binormal vectors on each Path3D curve point.
  4577. */
  4578. Path3D.prototype.getBinormals = function () {
  4579. return this._binormals;
  4580. };
  4581. /**
  4582. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4583. */
  4584. Path3D.prototype.getDistances = function () {
  4585. return this._distances;
  4586. };
  4587. /**
  4588. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4589. * Returns the same object updated.
  4590. */
  4591. Path3D.prototype.update = function (path, firstNormal) {
  4592. if (firstNormal === void 0) { firstNormal = null; }
  4593. for (var p = 0; p < path.length; p++) {
  4594. this._curve[p].x = path[p].x;
  4595. this._curve[p].y = path[p].y;
  4596. this._curve[p].z = path[p].z;
  4597. }
  4598. this._compute(firstNormal);
  4599. return this;
  4600. };
  4601. // private function compute() : computes tangents, normals and binormals
  4602. Path3D.prototype._compute = function (firstNormal) {
  4603. var l = this._curve.length;
  4604. // first and last tangents
  4605. this._tangents[0] = this._getFirstNonNullVector(0);
  4606. if (!this._raw) {
  4607. this._tangents[0].normalize();
  4608. }
  4609. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4610. if (!this._raw) {
  4611. this._tangents[l - 1].normalize();
  4612. }
  4613. // normals and binormals at first point : arbitrary vector with _normalVector()
  4614. var tg0 = this._tangents[0];
  4615. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4616. this._normals[0] = pp0;
  4617. if (!this._raw) {
  4618. this._normals[0].normalize();
  4619. }
  4620. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4621. if (!this._raw) {
  4622. this._binormals[0].normalize();
  4623. }
  4624. this._distances[0] = 0.0;
  4625. // normals and binormals : next points
  4626. var prev; // previous vector (segment)
  4627. var cur; // current vector (segment)
  4628. var curTang; // current tangent
  4629. // previous normal
  4630. var prevBinor; // previous binormal
  4631. for (var i = 1; i < l; i++) {
  4632. // tangents
  4633. prev = this._getLastNonNullVector(i);
  4634. if (i < l - 1) {
  4635. cur = this._getFirstNonNullVector(i);
  4636. this._tangents[i] = prev.add(cur);
  4637. this._tangents[i].normalize();
  4638. }
  4639. this._distances[i] = this._distances[i - 1] + prev.length();
  4640. // normals and binormals
  4641. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4642. curTang = this._tangents[i];
  4643. prevBinor = this._binormals[i - 1];
  4644. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4645. if (!this._raw) {
  4646. this._normals[i].normalize();
  4647. }
  4648. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4649. if (!this._raw) {
  4650. this._binormals[i].normalize();
  4651. }
  4652. }
  4653. };
  4654. // private function getFirstNonNullVector(index)
  4655. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4656. Path3D.prototype._getFirstNonNullVector = function (index) {
  4657. var i = 1;
  4658. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4659. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4660. i++;
  4661. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4662. }
  4663. return nNVector;
  4664. };
  4665. // private function getLastNonNullVector(index)
  4666. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4667. Path3D.prototype._getLastNonNullVector = function (index) {
  4668. var i = 1;
  4669. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4670. while (nLVector.length() === 0 && index > i + 1) {
  4671. i++;
  4672. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4673. }
  4674. return nLVector;
  4675. };
  4676. // private function normalVector(v0, vt, va) :
  4677. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4678. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4679. Path3D.prototype._normalVector = function (v0, vt, va) {
  4680. var normal0;
  4681. var tgl = vt.length();
  4682. if (tgl === 0.0) {
  4683. tgl = 1.0;
  4684. }
  4685. if (va === undefined || va === null) {
  4686. var point;
  4687. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4688. point = new Vector3(0.0, -1.0, 0.0);
  4689. }
  4690. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4691. point = new Vector3(1.0, 0.0, 0.0);
  4692. }
  4693. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4694. point = new Vector3(0.0, 0.0, 1.0);
  4695. }
  4696. else {
  4697. point = Vector3.Zero();
  4698. }
  4699. normal0 = Vector3.Cross(vt, point);
  4700. }
  4701. else {
  4702. normal0 = Vector3.Cross(vt, va);
  4703. Vector3.CrossToRef(normal0, vt, normal0);
  4704. }
  4705. normal0.normalize();
  4706. return normal0;
  4707. };
  4708. return Path3D;
  4709. }());
  4710. BABYLON.Path3D = Path3D;
  4711. var Curve3 = /** @class */ (function () {
  4712. /**
  4713. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4714. * A Curve3 is designed from a series of successive Vector3.
  4715. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4716. */
  4717. function Curve3(points) {
  4718. this._length = 0.0;
  4719. this._points = points;
  4720. this._length = this._computeLength(points);
  4721. }
  4722. /**
  4723. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4724. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4725. * @param v1 (Vector3) the control point
  4726. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4727. * @param nbPoints (integer) the wanted number of points in the curve
  4728. */
  4729. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4730. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4731. var bez = new Array();
  4732. var equation = function (t, val0, val1, val2) {
  4733. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4734. return res;
  4735. };
  4736. for (var i = 0; i <= nbPoints; i++) {
  4737. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  4738. }
  4739. return new Curve3(bez);
  4740. };
  4741. /**
  4742. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4743. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4744. * @param v1 (Vector3) the first control point
  4745. * @param v2 (Vector3) the second control point
  4746. * @param v3 (Vector3) the end point of the Cubic Bezier
  4747. * @param nbPoints (integer) the wanted number of points in the curve
  4748. */
  4749. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4750. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4751. var bez = new Array();
  4752. var equation = function (t, val0, val1, val2, val3) {
  4753. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  4754. return res;
  4755. };
  4756. for (var i = 0; i <= nbPoints; i++) {
  4757. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  4758. }
  4759. return new Curve3(bez);
  4760. };
  4761. /**
  4762. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4763. * @param p1 (Vector3) the origin point of the Hermite Spline
  4764. * @param t1 (Vector3) the tangent vector at the origin point
  4765. * @param p2 (Vector3) the end point of the Hermite Spline
  4766. * @param t2 (Vector3) the tangent vector at the end point
  4767. * @param nbPoints (integer) the wanted number of points in the curve
  4768. */
  4769. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4770. var hermite = new Array();
  4771. var step = 1.0 / nbPoints;
  4772. for (var i = 0; i <= nbPoints; i++) {
  4773. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4774. }
  4775. return new Curve3(hermite);
  4776. };
  4777. /**
  4778. * Returns a Curve3 object along a CatmullRom Spline curve :
  4779. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4780. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4781. */
  4782. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4783. var totalPoints = new Array();
  4784. totalPoints.push(points[0].clone());
  4785. Array.prototype.push.apply(totalPoints, points);
  4786. totalPoints.push(points[points.length - 1].clone());
  4787. var catmullRom = new Array();
  4788. var step = 1.0 / nbPoints;
  4789. var amount = 0.0;
  4790. for (var i = 0; i < totalPoints.length - 3; i++) {
  4791. amount = 0;
  4792. for (var c = 0; c < nbPoints; c++) {
  4793. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4794. amount += step;
  4795. }
  4796. }
  4797. i--;
  4798. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4799. return new Curve3(catmullRom);
  4800. };
  4801. /**
  4802. * Returns the Curve3 stored array of successive Vector3
  4803. */
  4804. Curve3.prototype.getPoints = function () {
  4805. return this._points;
  4806. };
  4807. /**
  4808. * Returns the computed length (float) of the curve.
  4809. */
  4810. Curve3.prototype.length = function () {
  4811. return this._length;
  4812. };
  4813. /**
  4814. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4815. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4816. * curveA and curveB keep unchanged.
  4817. */
  4818. Curve3.prototype.continue = function (curve) {
  4819. var lastPoint = this._points[this._points.length - 1];
  4820. var continuedPoints = this._points.slice();
  4821. var curvePoints = curve.getPoints();
  4822. for (var i = 1; i < curvePoints.length; i++) {
  4823. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4824. }
  4825. var continuedCurve = new Curve3(continuedPoints);
  4826. return continuedCurve;
  4827. };
  4828. Curve3.prototype._computeLength = function (path) {
  4829. var l = 0;
  4830. for (var i = 1; i < path.length; i++) {
  4831. l += (path[i].subtract(path[i - 1])).length();
  4832. }
  4833. return l;
  4834. };
  4835. return Curve3;
  4836. }());
  4837. BABYLON.Curve3 = Curve3;
  4838. // Vertex formats
  4839. var PositionNormalVertex = /** @class */ (function () {
  4840. function PositionNormalVertex(position, normal) {
  4841. if (position === void 0) { position = Vector3.Zero(); }
  4842. if (normal === void 0) { normal = Vector3.Up(); }
  4843. this.position = position;
  4844. this.normal = normal;
  4845. }
  4846. PositionNormalVertex.prototype.clone = function () {
  4847. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4848. };
  4849. return PositionNormalVertex;
  4850. }());
  4851. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4852. var PositionNormalTextureVertex = /** @class */ (function () {
  4853. function PositionNormalTextureVertex(position, normal, uv) {
  4854. if (position === void 0) { position = Vector3.Zero(); }
  4855. if (normal === void 0) { normal = Vector3.Up(); }
  4856. if (uv === void 0) { uv = Vector2.Zero(); }
  4857. this.position = position;
  4858. this.normal = normal;
  4859. this.uv = uv;
  4860. }
  4861. PositionNormalTextureVertex.prototype.clone = function () {
  4862. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4863. };
  4864. return PositionNormalTextureVertex;
  4865. }());
  4866. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4867. // Temporary pre-allocated objects for engine internal use
  4868. // usage in any internal function :
  4869. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4870. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4871. var Tmp = /** @class */ (function () {
  4872. function Tmp() {
  4873. }
  4874. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4875. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4876. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4877. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4878. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4879. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4880. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4881. Matrix.Zero(), Matrix.Zero(),
  4882. Matrix.Zero(), Matrix.Zero(),
  4883. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4884. return Tmp;
  4885. }());
  4886. BABYLON.Tmp = Tmp;
  4887. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4888. var MathTmp = /** @class */ (function () {
  4889. function MathTmp() {
  4890. }
  4891. MathTmp.Vector3 = [Vector3.Zero()];
  4892. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4893. MathTmp.Quaternion = [Quaternion.Zero()];
  4894. return MathTmp;
  4895. }());
  4896. })(BABYLON || (BABYLON = {}));
  4897. //# sourceMappingURL=babylon.math.js.map
  4898. var BABYLON;
  4899. (function (BABYLON) {
  4900. var Scalar = /** @class */ (function () {
  4901. function Scalar() {
  4902. }
  4903. /**
  4904. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4905. */
  4906. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4907. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4908. var num = a - b;
  4909. return -epsilon <= num && num <= epsilon;
  4910. };
  4911. /**
  4912. * Returns a string : the upper case translation of the number i to hexadecimal.
  4913. */
  4914. Scalar.ToHex = function (i) {
  4915. var str = i.toString(16);
  4916. if (i <= 15) {
  4917. return ("0" + str).toUpperCase();
  4918. }
  4919. return str.toUpperCase();
  4920. };
  4921. /**
  4922. * Returns -1 if value is negative and +1 is value is positive.
  4923. * Returns the value itself if it's equal to zero.
  4924. */
  4925. Scalar.Sign = function (value) {
  4926. value = +value; // convert to a number
  4927. if (value === 0 || isNaN(value))
  4928. return value;
  4929. return value > 0 ? 1 : -1;
  4930. };
  4931. /**
  4932. * Returns the value itself if it's between min and max.
  4933. * Returns min if the value is lower than min.
  4934. * Returns max if the value is greater than max.
  4935. */
  4936. Scalar.Clamp = function (value, min, max) {
  4937. if (min === void 0) { min = 0; }
  4938. if (max === void 0) { max = 1; }
  4939. return Math.min(max, Math.max(min, value));
  4940. };
  4941. /**
  4942. * Returns the log2 of value.
  4943. */
  4944. Scalar.Log2 = function (value) {
  4945. return Math.log(value) * Math.LOG2E;
  4946. };
  4947. /**
  4948. * Loops the value, so that it is never larger than length and never smaller than 0.
  4949. *
  4950. * This is similar to the modulo operator but it works with floating point numbers.
  4951. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4952. * With t = 5 and length = 2.5, the result would be 0.0.
  4953. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4954. */
  4955. Scalar.Repeat = function (value, length) {
  4956. return value - Math.floor(value / length) * length;
  4957. };
  4958. /**
  4959. * Normalize the value between 0.0 and 1.0 using min and max values
  4960. */
  4961. Scalar.Normalize = function (value, min, max) {
  4962. return (value - min) / (max - min);
  4963. };
  4964. /**
  4965. * Denormalize the value from 0.0 and 1.0 using min and max values
  4966. */
  4967. Scalar.Denormalize = function (normalized, min, max) {
  4968. return (normalized * (max - min) + min);
  4969. };
  4970. /**
  4971. * Calculates the shortest difference between two given angles given in degrees.
  4972. */
  4973. Scalar.DeltaAngle = function (current, target) {
  4974. var num = Scalar.Repeat(target - current, 360.0);
  4975. if (num > 180.0) {
  4976. num -= 360.0;
  4977. }
  4978. return num;
  4979. };
  4980. /**
  4981. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4982. *
  4983. * The returned value will move back and forth between 0 and length
  4984. */
  4985. Scalar.PingPong = function (tx, length) {
  4986. var t = Scalar.Repeat(tx, length * 2.0);
  4987. return length - Math.abs(t - length);
  4988. };
  4989. /**
  4990. * Interpolates between min and max with smoothing at the limits.
  4991. *
  4992. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4993. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4994. */
  4995. Scalar.SmoothStep = function (from, to, tx) {
  4996. var t = Scalar.Clamp(tx);
  4997. t = -2.0 * t * t * t + 3.0 * t * t;
  4998. return to * t + from * (1.0 - t);
  4999. };
  5000. /**
  5001. * Moves a value current towards target.
  5002. *
  5003. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5004. * Negative values of maxDelta pushes the value away from target.
  5005. */
  5006. Scalar.MoveTowards = function (current, target, maxDelta) {
  5007. var result = 0;
  5008. if (Math.abs(target - current) <= maxDelta) {
  5009. result = target;
  5010. }
  5011. else {
  5012. result = current + Scalar.Sign(target - current) * maxDelta;
  5013. }
  5014. return result;
  5015. };
  5016. /**
  5017. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5018. *
  5019. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5020. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5021. */
  5022. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5023. var num = Scalar.DeltaAngle(current, target);
  5024. var result = 0;
  5025. if (-maxDelta < num && num < maxDelta) {
  5026. result = target;
  5027. }
  5028. else {
  5029. target = current + num;
  5030. result = Scalar.MoveTowards(current, target, maxDelta);
  5031. }
  5032. return result;
  5033. };
  5034. /**
  5035. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5036. */
  5037. Scalar.Lerp = function (start, end, amount) {
  5038. return start + ((end - start) * amount);
  5039. };
  5040. /**
  5041. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5042. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5043. */
  5044. Scalar.LerpAngle = function (start, end, amount) {
  5045. var num = Scalar.Repeat(end - start, 360.0);
  5046. if (num > 180.0) {
  5047. num -= 360.0;
  5048. }
  5049. return start + num * Scalar.Clamp(amount);
  5050. };
  5051. /**
  5052. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5053. */
  5054. Scalar.InverseLerp = function (a, b, value) {
  5055. var result = 0;
  5056. if (a != b) {
  5057. result = Scalar.Clamp((value - a) / (b - a));
  5058. }
  5059. else {
  5060. result = 0.0;
  5061. }
  5062. return result;
  5063. };
  5064. /**
  5065. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5066. */
  5067. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5068. var squared = amount * amount;
  5069. var cubed = amount * squared;
  5070. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5071. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5072. var part3 = (cubed - (2.0 * squared)) + amount;
  5073. var part4 = cubed - squared;
  5074. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5075. };
  5076. /**
  5077. * Returns a random float number between and min and max values
  5078. */
  5079. Scalar.RandomRange = function (min, max) {
  5080. if (min === max)
  5081. return min;
  5082. return ((Math.random() * (max - min)) + min);
  5083. };
  5084. /**
  5085. * This function returns percentage of a number in a given range.
  5086. *
  5087. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5088. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5089. */
  5090. Scalar.RangeToPercent = function (number, min, max) {
  5091. return ((number - min) / (max - min));
  5092. };
  5093. /**
  5094. * This function returns number that corresponds to the percentage in a given range.
  5095. *
  5096. * PercentToRange(0.34,0,100) will return 34.
  5097. */
  5098. Scalar.PercentToRange = function (percent, min, max) {
  5099. return ((max - min) * percent + min);
  5100. };
  5101. return Scalar;
  5102. }());
  5103. BABYLON.Scalar = Scalar;
  5104. })(BABYLON || (BABYLON = {}));
  5105. //# sourceMappingURL=babylon.math.scalar.js.map
  5106. //# sourceMappingURL=babylon.mixins.js.map
  5107. var BABYLON;
  5108. (function (BABYLON) {
  5109. var __decoratorInitialStore = {};
  5110. var __mergedStore = {};
  5111. var _copySource = function (creationFunction, source, instanciate) {
  5112. var destination = creationFunction();
  5113. // Tags
  5114. if (BABYLON.Tags) {
  5115. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5116. }
  5117. var classStore = getMergedStore(destination);
  5118. // Properties
  5119. for (var property in classStore) {
  5120. var propertyDescriptor = classStore[property];
  5121. var sourceProperty = source[property];
  5122. var propertyType = propertyDescriptor.type;
  5123. if (sourceProperty !== undefined && sourceProperty !== null) {
  5124. switch (propertyType) {
  5125. case 0: // Value
  5126. case 6:// Mesh reference
  5127. destination[property] = sourceProperty;
  5128. break;
  5129. case 1:// Texture
  5130. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5131. break;
  5132. case 2: // Color3
  5133. case 3: // FresnelParameters
  5134. case 4: // Vector2
  5135. case 5: // Vector3
  5136. case 7:// Color Curves
  5137. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5138. break;
  5139. }
  5140. }
  5141. }
  5142. return destination;
  5143. };
  5144. function getDirectStore(target) {
  5145. var classKey = target.getClassName();
  5146. if (!__decoratorInitialStore[classKey]) {
  5147. __decoratorInitialStore[classKey] = {};
  5148. }
  5149. return __decoratorInitialStore[classKey];
  5150. }
  5151. /**
  5152. * Return the list of properties flagged as serializable
  5153. * @param target: host object
  5154. */
  5155. function getMergedStore(target) {
  5156. var classKey = target.getClassName();
  5157. if (__mergedStore[classKey]) {
  5158. return __mergedStore[classKey];
  5159. }
  5160. __mergedStore[classKey] = {};
  5161. var store = __mergedStore[classKey];
  5162. var currentTarget = target;
  5163. var currentKey = classKey;
  5164. while (currentKey) {
  5165. var initialStore = __decoratorInitialStore[currentKey];
  5166. for (var property in initialStore) {
  5167. store[property] = initialStore[property];
  5168. }
  5169. var parent_1 = void 0;
  5170. var done = false;
  5171. do {
  5172. parent_1 = Object.getPrototypeOf(currentTarget);
  5173. if (!parent_1.getClassName) {
  5174. done = true;
  5175. break;
  5176. }
  5177. if (parent_1.getClassName() !== currentKey) {
  5178. break;
  5179. }
  5180. currentTarget = parent_1;
  5181. } while (parent_1);
  5182. if (done) {
  5183. break;
  5184. }
  5185. currentKey = parent_1.getClassName();
  5186. currentTarget = parent_1;
  5187. }
  5188. return store;
  5189. }
  5190. function generateSerializableMember(type, sourceName) {
  5191. return function (target, propertyKey) {
  5192. var classStore = getDirectStore(target);
  5193. if (!classStore[propertyKey]) {
  5194. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5195. }
  5196. };
  5197. }
  5198. function generateExpandMember(setCallback, targetKey) {
  5199. if (targetKey === void 0) { targetKey = null; }
  5200. return function (target, propertyKey) {
  5201. var key = targetKey || ("_" + propertyKey);
  5202. Object.defineProperty(target, propertyKey, {
  5203. get: function () {
  5204. return this[key];
  5205. },
  5206. set: function (value) {
  5207. if (this[key] === value) {
  5208. return;
  5209. }
  5210. this[key] = value;
  5211. target[setCallback].apply(this);
  5212. },
  5213. enumerable: true,
  5214. configurable: true
  5215. });
  5216. };
  5217. }
  5218. function expandToProperty(callback, targetKey) {
  5219. if (targetKey === void 0) { targetKey = null; }
  5220. return generateExpandMember(callback, targetKey);
  5221. }
  5222. BABYLON.expandToProperty = expandToProperty;
  5223. function serialize(sourceName) {
  5224. return generateSerializableMember(0, sourceName); // value member
  5225. }
  5226. BABYLON.serialize = serialize;
  5227. function serializeAsTexture(sourceName) {
  5228. return generateSerializableMember(1, sourceName); // texture member
  5229. }
  5230. BABYLON.serializeAsTexture = serializeAsTexture;
  5231. function serializeAsColor3(sourceName) {
  5232. return generateSerializableMember(2, sourceName); // color3 member
  5233. }
  5234. BABYLON.serializeAsColor3 = serializeAsColor3;
  5235. function serializeAsFresnelParameters(sourceName) {
  5236. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5237. }
  5238. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5239. function serializeAsVector2(sourceName) {
  5240. return generateSerializableMember(4, sourceName); // vector2 member
  5241. }
  5242. BABYLON.serializeAsVector2 = serializeAsVector2;
  5243. function serializeAsVector3(sourceName) {
  5244. return generateSerializableMember(5, sourceName); // vector3 member
  5245. }
  5246. BABYLON.serializeAsVector3 = serializeAsVector3;
  5247. function serializeAsMeshReference(sourceName) {
  5248. return generateSerializableMember(6, sourceName); // mesh reference member
  5249. }
  5250. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5251. function serializeAsColorCurves(sourceName) {
  5252. return generateSerializableMember(7, sourceName); // color curves
  5253. }
  5254. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5255. function serializeAsColor4(sourceName) {
  5256. return generateSerializableMember(8, sourceName); // color 4
  5257. }
  5258. BABYLON.serializeAsColor4 = serializeAsColor4;
  5259. function serializeAsImageProcessingConfiguration(sourceName) {
  5260. return generateSerializableMember(9, sourceName); // image processing
  5261. }
  5262. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5263. var SerializationHelper = /** @class */ (function () {
  5264. function SerializationHelper() {
  5265. }
  5266. SerializationHelper.Serialize = function (entity, serializationObject) {
  5267. if (!serializationObject) {
  5268. serializationObject = {};
  5269. }
  5270. // Tags
  5271. if (BABYLON.Tags) {
  5272. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5273. }
  5274. var serializedProperties = getMergedStore(entity);
  5275. // Properties
  5276. for (var property in serializedProperties) {
  5277. var propertyDescriptor = serializedProperties[property];
  5278. var targetPropertyName = propertyDescriptor.sourceName || property;
  5279. var propertyType = propertyDescriptor.type;
  5280. var sourceProperty = entity[property];
  5281. if (sourceProperty !== undefined && sourceProperty !== null) {
  5282. switch (propertyType) {
  5283. case 0:// Value
  5284. serializationObject[targetPropertyName] = sourceProperty;
  5285. break;
  5286. case 1:// Texture
  5287. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5288. break;
  5289. case 2:// Color3
  5290. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5291. break;
  5292. case 3:// FresnelParameters
  5293. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5294. break;
  5295. case 4:// Vector2
  5296. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5297. break;
  5298. case 5:// Vector3
  5299. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5300. break;
  5301. case 6:// Mesh reference
  5302. serializationObject[targetPropertyName] = sourceProperty.id;
  5303. break;
  5304. case 7:// Color Curves
  5305. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5306. break;
  5307. case 8:// Color 4
  5308. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5309. break;
  5310. case 9:// Image Processing
  5311. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5312. break;
  5313. }
  5314. }
  5315. }
  5316. return serializationObject;
  5317. };
  5318. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5319. if (rootUrl === void 0) { rootUrl = null; }
  5320. var destination = creationFunction();
  5321. if (!rootUrl) {
  5322. rootUrl = "";
  5323. }
  5324. // Tags
  5325. if (BABYLON.Tags) {
  5326. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5327. }
  5328. var classStore = getMergedStore(destination);
  5329. // Properties
  5330. for (var property in classStore) {
  5331. var propertyDescriptor = classStore[property];
  5332. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5333. var propertyType = propertyDescriptor.type;
  5334. if (sourceProperty !== undefined && sourceProperty !== null) {
  5335. var dest = destination;
  5336. switch (propertyType) {
  5337. case 0:// Value
  5338. dest[property] = sourceProperty;
  5339. break;
  5340. case 1:// Texture
  5341. if (scene) {
  5342. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5343. }
  5344. break;
  5345. case 2:// Color3
  5346. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5347. break;
  5348. case 3:// FresnelParameters
  5349. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5350. break;
  5351. case 4:// Vector2
  5352. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5353. break;
  5354. case 5:// Vector3
  5355. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5356. break;
  5357. case 6:// Mesh reference
  5358. if (scene) {
  5359. dest[property] = scene.getLastMeshByID(sourceProperty);
  5360. }
  5361. break;
  5362. case 7:// Color Curves
  5363. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5364. break;
  5365. case 8:// Color 4
  5366. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5367. break;
  5368. case 9:// Image Processing
  5369. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5370. break;
  5371. }
  5372. }
  5373. }
  5374. return destination;
  5375. };
  5376. SerializationHelper.Clone = function (creationFunction, source) {
  5377. return _copySource(creationFunction, source, false);
  5378. };
  5379. SerializationHelper.Instanciate = function (creationFunction, source) {
  5380. return _copySource(creationFunction, source, true);
  5381. };
  5382. return SerializationHelper;
  5383. }());
  5384. BABYLON.SerializationHelper = SerializationHelper;
  5385. })(BABYLON || (BABYLON = {}));
  5386. //# sourceMappingURL=babylon.decorators.js.map
  5387. var BABYLON;
  5388. (function (BABYLON) {
  5389. /**
  5390. * A class serves as a medium between the observable and its observers
  5391. */
  5392. var EventState = /** @class */ (function () {
  5393. /**
  5394. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5395. */
  5396. function EventState(mask, skipNextObservers, target, currentTarget) {
  5397. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5398. this.initalize(mask, skipNextObservers, target, currentTarget);
  5399. }
  5400. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5401. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5402. this.mask = mask;
  5403. this.skipNextObservers = skipNextObservers;
  5404. this.target = target;
  5405. this.currentTarget = currentTarget;
  5406. return this;
  5407. };
  5408. return EventState;
  5409. }());
  5410. BABYLON.EventState = EventState;
  5411. /**
  5412. * Represent an Observer registered to a given Observable object.
  5413. */
  5414. var Observer = /** @class */ (function () {
  5415. function Observer(callback, mask, scope) {
  5416. if (scope === void 0) { scope = null; }
  5417. this.callback = callback;
  5418. this.mask = mask;
  5419. this.scope = scope;
  5420. }
  5421. return Observer;
  5422. }());
  5423. BABYLON.Observer = Observer;
  5424. /**
  5425. * Represent a list of observers registered to multiple Observables object.
  5426. */
  5427. var MultiObserver = /** @class */ (function () {
  5428. function MultiObserver() {
  5429. }
  5430. MultiObserver.prototype.dispose = function () {
  5431. if (this._observers && this._observables) {
  5432. for (var index = 0; index < this._observers.length; index++) {
  5433. this._observables[index].remove(this._observers[index]);
  5434. }
  5435. }
  5436. this._observers = null;
  5437. this._observables = null;
  5438. };
  5439. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5440. if (mask === void 0) { mask = -1; }
  5441. if (scope === void 0) { scope = null; }
  5442. var result = new MultiObserver();
  5443. result._observers = new Array();
  5444. result._observables = observables;
  5445. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5446. var observable = observables_1[_i];
  5447. var observer = observable.add(callback, mask, false, scope);
  5448. if (observer) {
  5449. result._observers.push(observer);
  5450. }
  5451. }
  5452. return result;
  5453. };
  5454. return MultiObserver;
  5455. }());
  5456. BABYLON.MultiObserver = MultiObserver;
  5457. /**
  5458. * The Observable class is a simple implementation of the Observable pattern.
  5459. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  5460. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5461. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  5462. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  5463. */
  5464. var Observable = /** @class */ (function () {
  5465. function Observable(onObserverAdded) {
  5466. this._observers = new Array();
  5467. this._eventState = new EventState(0);
  5468. if (onObserverAdded) {
  5469. this._onObserverAdded = onObserverAdded;
  5470. }
  5471. }
  5472. /**
  5473. * Create a new Observer with the specified callback
  5474. * @param callback the callback that will be executed for that Observer
  5475. * @param mask the mask used to filter observers
  5476. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  5477. * @param scope optional scope for the callback to be called from
  5478. */
  5479. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5480. if (mask === void 0) { mask = -1; }
  5481. if (insertFirst === void 0) { insertFirst = false; }
  5482. if (scope === void 0) { scope = null; }
  5483. if (!callback) {
  5484. return null;
  5485. }
  5486. var observer = new Observer(callback, mask, scope);
  5487. if (insertFirst) {
  5488. this._observers.unshift(observer);
  5489. }
  5490. else {
  5491. this._observers.push(observer);
  5492. }
  5493. if (this._onObserverAdded) {
  5494. this._onObserverAdded(observer);
  5495. }
  5496. return observer;
  5497. };
  5498. /**
  5499. * Remove an Observer from the Observable object
  5500. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5501. */
  5502. Observable.prototype.remove = function (observer) {
  5503. if (!observer) {
  5504. return false;
  5505. }
  5506. var index = this._observers.indexOf(observer);
  5507. if (index !== -1) {
  5508. this._observers.splice(index, 1);
  5509. return true;
  5510. }
  5511. return false;
  5512. };
  5513. /**
  5514. * Remove a callback from the Observable object
  5515. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5516. */
  5517. Observable.prototype.removeCallback = function (callback) {
  5518. for (var index = 0; index < this._observers.length; index++) {
  5519. if (this._observers[index].callback === callback) {
  5520. this._observers.splice(index, 1);
  5521. return true;
  5522. }
  5523. }
  5524. return false;
  5525. };
  5526. /**
  5527. * Notify all Observers by calling their respective callback with the given data
  5528. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5529. * @param eventData
  5530. * @param mask
  5531. */
  5532. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5533. if (mask === void 0) { mask = -1; }
  5534. if (!this._observers.length) {
  5535. return true;
  5536. }
  5537. var state = this._eventState;
  5538. state.mask = mask;
  5539. state.target = target;
  5540. state.currentTarget = currentTarget;
  5541. state.skipNextObservers = false;
  5542. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5543. var obs = _a[_i];
  5544. if (obs.mask & mask) {
  5545. if (obs.scope) {
  5546. obs.callback.apply(obs.scope, [eventData, state]);
  5547. }
  5548. else {
  5549. obs.callback(eventData, state);
  5550. }
  5551. }
  5552. if (state.skipNextObservers) {
  5553. return false;
  5554. }
  5555. }
  5556. return true;
  5557. };
  5558. /**
  5559. * Notify a specific observer
  5560. * @param eventData
  5561. * @param mask
  5562. */
  5563. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5564. if (mask === void 0) { mask = -1; }
  5565. var state = this._eventState;
  5566. state.mask = mask;
  5567. state.skipNextObservers = false;
  5568. observer.callback(eventData, state);
  5569. };
  5570. /**
  5571. * return true is the Observable has at least one Observer registered
  5572. */
  5573. Observable.prototype.hasObservers = function () {
  5574. return this._observers.length > 0;
  5575. };
  5576. /**
  5577. * Clear the list of observers
  5578. */
  5579. Observable.prototype.clear = function () {
  5580. this._observers = new Array();
  5581. this._onObserverAdded = null;
  5582. };
  5583. /**
  5584. * Clone the current observable
  5585. */
  5586. Observable.prototype.clone = function () {
  5587. var result = new Observable();
  5588. result._observers = this._observers.slice(0);
  5589. return result;
  5590. };
  5591. /**
  5592. * Does this observable handles observer registered with a given mask
  5593. * @param {number} trigger - the mask to be tested
  5594. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5595. **/
  5596. Observable.prototype.hasSpecificMask = function (mask) {
  5597. if (mask === void 0) { mask = -1; }
  5598. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5599. var obs = _a[_i];
  5600. if (obs.mask & mask || obs.mask === mask) {
  5601. return true;
  5602. }
  5603. }
  5604. return false;
  5605. };
  5606. return Observable;
  5607. }());
  5608. BABYLON.Observable = Observable;
  5609. })(BABYLON || (BABYLON = {}));
  5610. //# sourceMappingURL=babylon.observable.js.map
  5611. var BABYLON;
  5612. (function (BABYLON) {
  5613. var SmartArray = /** @class */ (function () {
  5614. function SmartArray(capacity) {
  5615. this.length = 0;
  5616. this.data = new Array(capacity);
  5617. this._id = SmartArray._GlobalId++;
  5618. }
  5619. SmartArray.prototype.push = function (value) {
  5620. this.data[this.length++] = value;
  5621. if (this.length > this.data.length) {
  5622. this.data.length *= 2;
  5623. }
  5624. };
  5625. SmartArray.prototype.forEach = function (func) {
  5626. for (var index = 0; index < this.length; index++) {
  5627. func(this.data[index]);
  5628. }
  5629. };
  5630. SmartArray.prototype.sort = function (compareFn) {
  5631. this.data.sort(compareFn);
  5632. };
  5633. SmartArray.prototype.reset = function () {
  5634. this.length = 0;
  5635. };
  5636. SmartArray.prototype.dispose = function () {
  5637. this.reset();
  5638. if (this.data) {
  5639. this.data.length = 0;
  5640. this.data = [];
  5641. }
  5642. };
  5643. SmartArray.prototype.concat = function (array) {
  5644. if (array.length === 0) {
  5645. return;
  5646. }
  5647. if (this.length + array.length > this.data.length) {
  5648. this.data.length = (this.length + array.length) * 2;
  5649. }
  5650. for (var index = 0; index < array.length; index++) {
  5651. this.data[this.length++] = (array.data || array)[index];
  5652. }
  5653. };
  5654. SmartArray.prototype.indexOf = function (value) {
  5655. var position = this.data.indexOf(value);
  5656. if (position >= this.length) {
  5657. return -1;
  5658. }
  5659. return position;
  5660. };
  5661. SmartArray.prototype.contains = function (value) {
  5662. return this.data.indexOf(value) !== -1;
  5663. };
  5664. // Statics
  5665. SmartArray._GlobalId = 0;
  5666. return SmartArray;
  5667. }());
  5668. BABYLON.SmartArray = SmartArray;
  5669. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5670. __extends(SmartArrayNoDuplicate, _super);
  5671. function SmartArrayNoDuplicate() {
  5672. var _this = _super !== null && _super.apply(this, arguments) || this;
  5673. _this._duplicateId = 0;
  5674. return _this;
  5675. }
  5676. SmartArrayNoDuplicate.prototype.push = function (value) {
  5677. _super.prototype.push.call(this, value);
  5678. if (!value.__smartArrayFlags) {
  5679. value.__smartArrayFlags = {};
  5680. }
  5681. value.__smartArrayFlags[this._id] = this._duplicateId;
  5682. };
  5683. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5684. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5685. return false;
  5686. }
  5687. this.push(value);
  5688. return true;
  5689. };
  5690. SmartArrayNoDuplicate.prototype.reset = function () {
  5691. _super.prototype.reset.call(this);
  5692. this._duplicateId++;
  5693. };
  5694. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5695. if (array.length === 0) {
  5696. return;
  5697. }
  5698. if (this.length + array.length > this.data.length) {
  5699. this.data.length = (this.length + array.length) * 2;
  5700. }
  5701. for (var index = 0; index < array.length; index++) {
  5702. var item = (array.data || array)[index];
  5703. this.pushNoDuplicate(item);
  5704. }
  5705. };
  5706. return SmartArrayNoDuplicate;
  5707. }(SmartArray));
  5708. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5709. })(BABYLON || (BABYLON = {}));
  5710. //# sourceMappingURL=babylon.smartArray.js.map
  5711. var BABYLON;
  5712. (function (BABYLON) {
  5713. // Screenshots
  5714. var screenshotCanvas;
  5715. var cloneValue = function (source, destinationObject) {
  5716. if (!source)
  5717. return null;
  5718. if (source instanceof BABYLON.Mesh) {
  5719. return null;
  5720. }
  5721. if (source instanceof BABYLON.SubMesh) {
  5722. return source.clone(destinationObject);
  5723. }
  5724. else if (source.clone) {
  5725. return source.clone();
  5726. }
  5727. return null;
  5728. };
  5729. var Tools = /** @class */ (function () {
  5730. function Tools() {
  5731. }
  5732. ;
  5733. /**
  5734. * Interpolates between a and b via alpha
  5735. * @param a The lower value (returned when alpha = 0)
  5736. * @param b The upper value (returned when alpha = 1)
  5737. * @param alpha The interpolation-factor
  5738. * @return The mixed value
  5739. */
  5740. Tools.Mix = function (a, b, alpha) {
  5741. return a * (1 - alpha) + b * alpha;
  5742. };
  5743. Tools.Instantiate = function (className) {
  5744. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5745. return Tools.RegisteredExternalClasses[className];
  5746. }
  5747. var arr = className.split(".");
  5748. var fn = (window || this);
  5749. for (var i = 0, len = arr.length; i < len; i++) {
  5750. fn = fn[arr[i]];
  5751. }
  5752. if (typeof fn !== "function") {
  5753. return null;
  5754. }
  5755. return fn;
  5756. };
  5757. Tools.SetImmediate = function (action) {
  5758. if (window.setImmediate) {
  5759. window.setImmediate(action);
  5760. }
  5761. else {
  5762. setTimeout(action, 1);
  5763. }
  5764. };
  5765. Tools.IsExponentOfTwo = function (value) {
  5766. var count = 1;
  5767. do {
  5768. count *= 2;
  5769. } while (count < value);
  5770. return count === value;
  5771. };
  5772. /**
  5773. * Find the next highest power of two.
  5774. * @param x Number to start search from.
  5775. * @return Next highest power of two.
  5776. */
  5777. Tools.CeilingPOT = function (x) {
  5778. x--;
  5779. x |= x >> 1;
  5780. x |= x >> 2;
  5781. x |= x >> 4;
  5782. x |= x >> 8;
  5783. x |= x >> 16;
  5784. x++;
  5785. return x;
  5786. };
  5787. /**
  5788. * Find the next lowest power of two.
  5789. * @param x Number to start search from.
  5790. * @return Next lowest power of two.
  5791. */
  5792. Tools.FloorPOT = function (x) {
  5793. x = x | (x >> 1);
  5794. x = x | (x >> 2);
  5795. x = x | (x >> 4);
  5796. x = x | (x >> 8);
  5797. x = x | (x >> 16);
  5798. return x - (x >> 1);
  5799. };
  5800. /**
  5801. * Find the nearest power of two.
  5802. * @param x Number to start search from.
  5803. * @return Next nearest power of two.
  5804. */
  5805. Tools.NearestPOT = function (x) {
  5806. var c = Tools.CeilingPOT(x);
  5807. var f = Tools.FloorPOT(x);
  5808. return (c - x) > (x - f) ? f : c;
  5809. };
  5810. Tools.GetExponentOfTwo = function (value, max, mode) {
  5811. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5812. var pot;
  5813. switch (mode) {
  5814. case BABYLON.Engine.SCALEMODE_FLOOR:
  5815. pot = Tools.FloorPOT(value);
  5816. break;
  5817. case BABYLON.Engine.SCALEMODE_NEAREST:
  5818. pot = Tools.NearestPOT(value);
  5819. break;
  5820. case BABYLON.Engine.SCALEMODE_CEILING:
  5821. default:
  5822. pot = Tools.CeilingPOT(value);
  5823. break;
  5824. }
  5825. return Math.min(pot, max);
  5826. };
  5827. Tools.GetFilename = function (path) {
  5828. var index = path.lastIndexOf("/");
  5829. if (index < 0)
  5830. return path;
  5831. return path.substring(index + 1);
  5832. };
  5833. Tools.GetDOMTextContent = function (element) {
  5834. var result = "";
  5835. var child = element.firstChild;
  5836. while (child) {
  5837. if (child.nodeType === 3) {
  5838. result += child.textContent;
  5839. }
  5840. child = child.nextSibling;
  5841. }
  5842. return result;
  5843. };
  5844. Tools.ToDegrees = function (angle) {
  5845. return angle * 180 / Math.PI;
  5846. };
  5847. Tools.ToRadians = function (angle) {
  5848. return angle * Math.PI / 180;
  5849. };
  5850. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5851. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5852. var output = "";
  5853. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5854. var i = 0;
  5855. var bytes = new Uint8Array(buffer);
  5856. while (i < bytes.length) {
  5857. chr1 = bytes[i++];
  5858. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5859. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5860. enc1 = chr1 >> 2;
  5861. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5862. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5863. enc4 = chr3 & 63;
  5864. if (isNaN(chr2)) {
  5865. enc3 = enc4 = 64;
  5866. }
  5867. else if (isNaN(chr3)) {
  5868. enc4 = 64;
  5869. }
  5870. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5871. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5872. }
  5873. return "data:image/png;base64," + output;
  5874. };
  5875. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5876. if (bias === void 0) { bias = null; }
  5877. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5878. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5879. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5880. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5881. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5882. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5883. }
  5884. if (bias) {
  5885. minimum.x -= minimum.x * bias.x + bias.y;
  5886. minimum.y -= minimum.y * bias.x + bias.y;
  5887. minimum.z -= minimum.z * bias.x + bias.y;
  5888. maximum.x += maximum.x * bias.x + bias.y;
  5889. maximum.y += maximum.y * bias.x + bias.y;
  5890. maximum.z += maximum.z * bias.x + bias.y;
  5891. }
  5892. return {
  5893. minimum: minimum,
  5894. maximum: maximum
  5895. };
  5896. };
  5897. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5898. if (bias === void 0) { bias = null; }
  5899. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5900. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5901. if (!stride) {
  5902. stride = 3;
  5903. }
  5904. for (var index = start; index < start + count; index++) {
  5905. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5906. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5907. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5908. }
  5909. if (bias) {
  5910. minimum.x -= minimum.x * bias.x + bias.y;
  5911. minimum.y -= minimum.y * bias.x + bias.y;
  5912. minimum.z -= minimum.z * bias.x + bias.y;
  5913. maximum.x += maximum.x * bias.x + bias.y;
  5914. maximum.y += maximum.y * bias.x + bias.y;
  5915. maximum.z += maximum.z * bias.x + bias.y;
  5916. }
  5917. return {
  5918. minimum: minimum,
  5919. maximum: maximum
  5920. };
  5921. };
  5922. Tools.Vector2ArrayFeeder = function (array) {
  5923. return function (index) {
  5924. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5925. var length = isFloatArray ? array.length / 2 : array.length;
  5926. if (index >= length) {
  5927. return null;
  5928. }
  5929. if (isFloatArray) {
  5930. var fa = array;
  5931. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5932. }
  5933. var a = array;
  5934. return a[index];
  5935. };
  5936. };
  5937. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5938. if (bias === void 0) { bias = null; }
  5939. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5940. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5941. var i = 0;
  5942. var cur = feeder(i++);
  5943. while (cur) {
  5944. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5945. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5946. cur = feeder(i++);
  5947. }
  5948. if (bias) {
  5949. minimum.x -= minimum.x * bias.x + bias.y;
  5950. minimum.y -= minimum.y * bias.x + bias.y;
  5951. maximum.x += maximum.x * bias.x + bias.y;
  5952. maximum.y += maximum.y * bias.x + bias.y;
  5953. }
  5954. return {
  5955. minimum: minimum,
  5956. maximum: maximum
  5957. };
  5958. };
  5959. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5960. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5961. return null;
  5962. return Array.isArray(obj) ? obj : [obj];
  5963. };
  5964. // Misc.
  5965. Tools.GetPointerPrefix = function () {
  5966. var eventPrefix = "pointer";
  5967. // Check if pointer events are supported
  5968. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  5969. eventPrefix = "mouse";
  5970. }
  5971. return eventPrefix;
  5972. };
  5973. /**
  5974. * @param func - the function to be called
  5975. * @param requester - the object that will request the next frame. Falls back to window.
  5976. */
  5977. Tools.QueueNewFrame = function (func, requester) {
  5978. if (!Tools.IsWindowObjectExist()) {
  5979. return setTimeout(func, 16);
  5980. }
  5981. if (!requester) {
  5982. requester = window;
  5983. }
  5984. if (requester.requestAnimationFrame) {
  5985. return requester.requestAnimationFrame(func);
  5986. }
  5987. else if (requester.msRequestAnimationFrame) {
  5988. return requester.msRequestAnimationFrame(func);
  5989. }
  5990. else if (requester.webkitRequestAnimationFrame) {
  5991. return requester.webkitRequestAnimationFrame(func);
  5992. }
  5993. else if (requester.mozRequestAnimationFrame) {
  5994. return requester.mozRequestAnimationFrame(func);
  5995. }
  5996. else if (requester.oRequestAnimationFrame) {
  5997. return requester.oRequestAnimationFrame(func);
  5998. }
  5999. else {
  6000. return window.setTimeout(func, 16);
  6001. }
  6002. };
  6003. Tools.RequestFullscreen = function (element) {
  6004. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6005. if (!requestFunction)
  6006. return;
  6007. requestFunction.call(element);
  6008. };
  6009. Tools.ExitFullscreen = function () {
  6010. if (document.exitFullscreen) {
  6011. document.exitFullscreen();
  6012. }
  6013. else if (document.mozCancelFullScreen) {
  6014. document.mozCancelFullScreen();
  6015. }
  6016. else if (document.webkitCancelFullScreen) {
  6017. document.webkitCancelFullScreen();
  6018. }
  6019. else if (document.msCancelFullScreen) {
  6020. document.msCancelFullScreen();
  6021. }
  6022. };
  6023. Tools.SetCorsBehavior = function (url, img) {
  6024. if (Tools.CorsBehavior) {
  6025. switch (typeof (Tools.CorsBehavior)) {
  6026. case "function":
  6027. var result = Tools.CorsBehavior(url);
  6028. if (result) {
  6029. img.crossOrigin = result;
  6030. }
  6031. break;
  6032. case "string":
  6033. default:
  6034. img.crossOrigin = Tools.CorsBehavior;
  6035. break;
  6036. }
  6037. }
  6038. };
  6039. // External files
  6040. Tools.CleanUrl = function (url) {
  6041. url = url.replace(/#/mg, "%23");
  6042. return url;
  6043. };
  6044. Tools.LoadImage = function (url, onLoad, onError, database) {
  6045. if (url instanceof ArrayBuffer) {
  6046. url = Tools.EncodeArrayBufferTobase64(url);
  6047. }
  6048. url = Tools.CleanUrl(url);
  6049. url = Tools.PreprocessUrl(url);
  6050. var img = new Image();
  6051. if (url.substr(0, 5) !== "data:") {
  6052. Tools.SetCorsBehavior(url, img);
  6053. }
  6054. img.onload = function () {
  6055. onLoad(img);
  6056. };
  6057. img.onerror = function (err) {
  6058. Tools.Error("Error while trying to load image: " + url);
  6059. if (Tools.UseFallbackTexture) {
  6060. img.src = Tools.fallbackTexture;
  6061. onLoad(img);
  6062. }
  6063. else {
  6064. onError("Error while trying to load image: " + url, err);
  6065. }
  6066. };
  6067. var noIndexedDB = function () {
  6068. img.src = url;
  6069. };
  6070. var loadFromIndexedDB = function () {
  6071. if (database) {
  6072. database.loadImageFromDB(url, img);
  6073. }
  6074. };
  6075. //ANY database to do!
  6076. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6077. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6078. }
  6079. else {
  6080. if (url.indexOf("file:") !== 0) {
  6081. noIndexedDB();
  6082. }
  6083. else {
  6084. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6085. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6086. try {
  6087. var blobURL;
  6088. try {
  6089. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6090. }
  6091. catch (ex) {
  6092. // Chrome doesn't support oneTimeOnly parameter
  6093. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6094. }
  6095. img.src = blobURL;
  6096. }
  6097. catch (e) {
  6098. img.src = "";
  6099. }
  6100. }
  6101. else {
  6102. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  6103. img.src = Tools.fallbackTexture;
  6104. }
  6105. }
  6106. }
  6107. return img;
  6108. };
  6109. //ANY
  6110. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  6111. url = Tools.CleanUrl(url);
  6112. url = Tools.PreprocessUrl(url);
  6113. var request = null;
  6114. var noIndexedDB = function () {
  6115. request = new XMLHttpRequest();
  6116. var loadUrl = Tools.BaseUrl + url;
  6117. request.open('GET', loadUrl, true);
  6118. if (useArrayBuffer) {
  6119. request.responseType = "arraybuffer";
  6120. }
  6121. if (progressCallBack) {
  6122. request.onprogress = progressCallBack;
  6123. }
  6124. request.onreadystatechange = function () {
  6125. var req = request;
  6126. // In case of undefined state in some browsers.
  6127. if (req.readyState === (XMLHttpRequest.DONE || 4)) {
  6128. req.onreadystatechange = function () { }; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  6129. if (req.status >= 200 && req.status < 300 || (!Tools.IsWindowObjectExist() && (req.status === 0))) {
  6130. callback(!useArrayBuffer ? req.responseText : req.response);
  6131. }
  6132. else {
  6133. var e = new Error("Error status: " + req.status + " - Unable to load " + loadUrl);
  6134. if (onError) {
  6135. onError(req, e);
  6136. }
  6137. else {
  6138. throw e;
  6139. }
  6140. }
  6141. }
  6142. };
  6143. request.send(null);
  6144. };
  6145. var loadFromIndexedDB = function () {
  6146. if (database) {
  6147. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  6148. }
  6149. };
  6150. if (url.indexOf("file:") !== -1) {
  6151. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6152. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6153. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  6154. }
  6155. else {
  6156. var errorMessage = "File: " + fileName + " not found. Did you forget to provide it?";
  6157. if (onError) {
  6158. var e = new Error(errorMessage);
  6159. onError(undefined, e);
  6160. }
  6161. else {
  6162. Tools.Error(errorMessage);
  6163. }
  6164. }
  6165. }
  6166. else {
  6167. // Caching all files
  6168. if (database && database.enableSceneOffline) {
  6169. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6170. }
  6171. else {
  6172. noIndexedDB();
  6173. }
  6174. }
  6175. return request;
  6176. };
  6177. /**
  6178. * Load a script (identified by an url). When the url returns, the
  6179. * content of this file is added into a new script element, attached to the DOM (body element)
  6180. */
  6181. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6182. var head = document.getElementsByTagName('head')[0];
  6183. var script = document.createElement('script');
  6184. script.type = 'text/javascript';
  6185. script.src = scriptUrl;
  6186. script.onload = function () {
  6187. if (onSuccess) {
  6188. onSuccess();
  6189. }
  6190. };
  6191. script.onerror = function (e) {
  6192. if (onError) {
  6193. onError("Unable to load script", e);
  6194. }
  6195. };
  6196. head.appendChild(script);
  6197. };
  6198. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6199. var reader = new FileReader();
  6200. reader.onload = function (e) {
  6201. //target doesn't have result from ts 1.3
  6202. callback(e.target['result']);
  6203. };
  6204. reader.onprogress = progressCallback;
  6205. reader.readAsDataURL(fileToLoad);
  6206. };
  6207. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6208. var reader = new FileReader();
  6209. reader.onerror = function (e) {
  6210. Tools.Log("Error while reading file: " + fileToLoad.name);
  6211. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6212. };
  6213. reader.onload = function (e) {
  6214. //target doesn't have result from ts 1.3
  6215. callback(e.target['result']);
  6216. };
  6217. if (progressCallBack) {
  6218. reader.onprogress = progressCallBack;
  6219. }
  6220. if (!useArrayBuffer) {
  6221. // Asynchronous read
  6222. reader.readAsText(fileToLoad);
  6223. }
  6224. else {
  6225. reader.readAsArrayBuffer(fileToLoad);
  6226. }
  6227. };
  6228. //returns a downloadable url to a file content.
  6229. Tools.FileAsURL = function (content) {
  6230. var fileBlob = new Blob([content]);
  6231. var url = window.URL || window.webkitURL;
  6232. var link = url.createObjectURL(fileBlob);
  6233. return link;
  6234. };
  6235. // Misc.
  6236. Tools.Format = function (value, decimals) {
  6237. if (decimals === void 0) { decimals = 2; }
  6238. return value.toFixed(decimals);
  6239. };
  6240. Tools.CheckExtends = function (v, min, max) {
  6241. if (v.x < min.x)
  6242. min.x = v.x;
  6243. if (v.y < min.y)
  6244. min.y = v.y;
  6245. if (v.z < min.z)
  6246. min.z = v.z;
  6247. if (v.x > max.x)
  6248. max.x = v.x;
  6249. if (v.y > max.y)
  6250. max.y = v.y;
  6251. if (v.z > max.z)
  6252. max.z = v.z;
  6253. };
  6254. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6255. for (var prop in source) {
  6256. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6257. continue;
  6258. }
  6259. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6260. continue;
  6261. }
  6262. var sourceValue = source[prop];
  6263. var typeOfSourceValue = typeof sourceValue;
  6264. if (typeOfSourceValue === "function") {
  6265. continue;
  6266. }
  6267. if (typeOfSourceValue === "object") {
  6268. if (sourceValue instanceof Array) {
  6269. destination[prop] = [];
  6270. if (sourceValue.length > 0) {
  6271. if (typeof sourceValue[0] == "object") {
  6272. for (var index = 0; index < sourceValue.length; index++) {
  6273. var clonedValue = cloneValue(sourceValue[index], destination);
  6274. if (destination[prop].indexOf(clonedValue) === -1) {
  6275. destination[prop].push(clonedValue);
  6276. }
  6277. }
  6278. }
  6279. else {
  6280. destination[prop] = sourceValue.slice(0);
  6281. }
  6282. }
  6283. }
  6284. else {
  6285. destination[prop] = cloneValue(sourceValue, destination);
  6286. }
  6287. }
  6288. else {
  6289. destination[prop] = sourceValue;
  6290. }
  6291. }
  6292. };
  6293. Tools.IsEmpty = function (obj) {
  6294. for (var i in obj) {
  6295. if (obj.hasOwnProperty(i)) {
  6296. return false;
  6297. }
  6298. }
  6299. return true;
  6300. };
  6301. Tools.RegisterTopRootEvents = function (events) {
  6302. for (var index = 0; index < events.length; index++) {
  6303. var event = events[index];
  6304. window.addEventListener(event.name, event.handler, false);
  6305. try {
  6306. if (window.parent) {
  6307. window.parent.addEventListener(event.name, event.handler, false);
  6308. }
  6309. }
  6310. catch (e) {
  6311. // Silently fails...
  6312. }
  6313. }
  6314. };
  6315. Tools.UnregisterTopRootEvents = function (events) {
  6316. for (var index = 0; index < events.length; index++) {
  6317. var event = events[index];
  6318. window.removeEventListener(event.name, event.handler);
  6319. try {
  6320. if (window.parent) {
  6321. window.parent.removeEventListener(event.name, event.handler);
  6322. }
  6323. }
  6324. catch (e) {
  6325. // Silently fails...
  6326. }
  6327. }
  6328. };
  6329. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  6330. if (mimeType === void 0) { mimeType = "image/png"; }
  6331. // Read the contents of the framebuffer
  6332. var numberOfChannelsByLine = width * 4;
  6333. var halfHeight = height / 2;
  6334. //Reading datas from WebGL
  6335. var data = engine.readPixels(0, 0, width, height);
  6336. //To flip image on Y axis.
  6337. for (var i = 0; i < halfHeight; i++) {
  6338. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6339. var currentCell = j + i * numberOfChannelsByLine;
  6340. var targetLine = height - i - 1;
  6341. var targetCell = j + targetLine * numberOfChannelsByLine;
  6342. var temp = data[currentCell];
  6343. data[currentCell] = data[targetCell];
  6344. data[targetCell] = temp;
  6345. }
  6346. }
  6347. // Create a 2D canvas to store the result
  6348. if (!screenshotCanvas) {
  6349. screenshotCanvas = document.createElement('canvas');
  6350. }
  6351. screenshotCanvas.width = width;
  6352. screenshotCanvas.height = height;
  6353. var context = screenshotCanvas.getContext('2d');
  6354. if (context) {
  6355. // Copy the pixels to a 2D canvas
  6356. var imageData = context.createImageData(width, height);
  6357. var castData = (imageData.data);
  6358. castData.set(data);
  6359. context.putImageData(imageData, 0, 0);
  6360. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6361. }
  6362. };
  6363. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6364. if (mimeType === void 0) { mimeType = "image/png"; }
  6365. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6366. if (successCallback) {
  6367. successCallback(base64Image);
  6368. }
  6369. else {
  6370. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6371. if (("download" in document.createElement("a"))) {
  6372. var a = window.document.createElement("a");
  6373. a.href = base64Image;
  6374. var date = new Date();
  6375. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6376. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6377. window.document.body.appendChild(a);
  6378. a.addEventListener("click", function () {
  6379. if (a.parentElement) {
  6380. a.parentElement.removeChild(a);
  6381. }
  6382. });
  6383. a.click();
  6384. //Or opening a new tab with the image if it is not possible to automatically start download.
  6385. }
  6386. else {
  6387. var newWindow = window.open("");
  6388. var img = newWindow.document.createElement("img");
  6389. img.src = base64Image;
  6390. newWindow.document.body.appendChild(img);
  6391. }
  6392. }
  6393. };
  6394. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6395. if (mimeType === void 0) { mimeType = "image/png"; }
  6396. var width;
  6397. var height;
  6398. // If a precision value is specified
  6399. if (size.precision) {
  6400. width = Math.round(engine.getRenderWidth() * size.precision);
  6401. height = Math.round(width / engine.getAspectRatio(camera));
  6402. }
  6403. else if (size.width && size.height) {
  6404. width = size.width;
  6405. height = size.height;
  6406. }
  6407. else if (size.width && !size.height) {
  6408. width = size.width;
  6409. height = Math.round(width / engine.getAspectRatio(camera));
  6410. }
  6411. else if (size.height && !size.width) {
  6412. height = size.height;
  6413. width = Math.round(height * engine.getAspectRatio(camera));
  6414. }
  6415. else if (!isNaN(size)) {
  6416. height = size;
  6417. width = size;
  6418. }
  6419. else {
  6420. Tools.Error("Invalid 'size' parameter !");
  6421. return;
  6422. }
  6423. if (!screenshotCanvas) {
  6424. screenshotCanvas = document.createElement('canvas');
  6425. }
  6426. screenshotCanvas.width = width;
  6427. screenshotCanvas.height = height;
  6428. var renderContext = screenshotCanvas.getContext("2d");
  6429. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6430. var newWidth = width;
  6431. var newHeight = newWidth / ratio;
  6432. if (newHeight > height) {
  6433. newHeight = height;
  6434. newWidth = newHeight * ratio;
  6435. }
  6436. var offsetX = Math.max(0, width - newWidth) / 2;
  6437. var offsetY = Math.max(0, height - newHeight) / 2;
  6438. var renderingCanvas = engine.getRenderingCanvas();
  6439. if (renderContext && renderingCanvas) {
  6440. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6441. }
  6442. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6443. };
  6444. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6445. if (mimeType === void 0) { mimeType = "image/png"; }
  6446. if (samples === void 0) { samples = 1; }
  6447. var width;
  6448. var height;
  6449. //If a precision value is specified
  6450. if (size.precision) {
  6451. width = Math.round(engine.getRenderWidth() * size.precision);
  6452. height = Math.round(width / engine.getAspectRatio(camera));
  6453. size = { width: width, height: height };
  6454. }
  6455. else if (size.width && size.height) {
  6456. width = size.width;
  6457. height = size.height;
  6458. }
  6459. else if (size.width && !size.height) {
  6460. width = size.width;
  6461. height = Math.round(width / engine.getAspectRatio(camera));
  6462. size = { width: width, height: height };
  6463. }
  6464. else if (size.height && !size.width) {
  6465. height = size.height;
  6466. width = Math.round(height * engine.getAspectRatio(camera));
  6467. size = { width: width, height: height };
  6468. }
  6469. else if (!isNaN(size)) {
  6470. height = size;
  6471. width = size;
  6472. }
  6473. else {
  6474. Tools.Error("Invalid 'size' parameter !");
  6475. return;
  6476. }
  6477. var scene = camera.getScene();
  6478. var previousCamera = null;
  6479. if (scene.activeCamera !== camera) {
  6480. previousCamera = scene.activeCamera;
  6481. scene.activeCamera = camera;
  6482. }
  6483. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6484. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6485. texture.renderList = null;
  6486. texture.samples = samples;
  6487. texture.onAfterRenderObservable.add(function () {
  6488. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6489. });
  6490. scene.incrementRenderId();
  6491. scene.resetCachedMaterial();
  6492. texture.render(true);
  6493. texture.dispose();
  6494. if (previousCamera) {
  6495. scene.activeCamera = previousCamera;
  6496. }
  6497. camera.getProjectionMatrix(true); // Force cache refresh;
  6498. };
  6499. // XHR response validator for local file scenario
  6500. Tools.ValidateXHRData = function (xhr, dataType) {
  6501. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6502. if (dataType === void 0) { dataType = 7; }
  6503. try {
  6504. if (dataType & 1) {
  6505. if (xhr.responseText && xhr.responseText.length > 0) {
  6506. return true;
  6507. }
  6508. else if (dataType === 1) {
  6509. return false;
  6510. }
  6511. }
  6512. if (dataType & 2) {
  6513. // Check header width and height since there is no "TGA" magic number
  6514. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6515. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6516. return true;
  6517. }
  6518. else if (dataType === 2) {
  6519. return false;
  6520. }
  6521. }
  6522. if (dataType & 4) {
  6523. // Check for the "DDS" magic number
  6524. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6525. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6526. return true;
  6527. }
  6528. else {
  6529. return false;
  6530. }
  6531. }
  6532. }
  6533. catch (e) {
  6534. // Global protection
  6535. }
  6536. return false;
  6537. };
  6538. /**
  6539. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6540. * Be aware Math.random() could cause collisions, but:
  6541. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  6542. */
  6543. Tools.RandomId = function () {
  6544. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6545. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6546. return v.toString(16);
  6547. });
  6548. };
  6549. Object.defineProperty(Tools, "NoneLogLevel", {
  6550. get: function () {
  6551. return Tools._NoneLogLevel;
  6552. },
  6553. enumerable: true,
  6554. configurable: true
  6555. });
  6556. Object.defineProperty(Tools, "MessageLogLevel", {
  6557. get: function () {
  6558. return Tools._MessageLogLevel;
  6559. },
  6560. enumerable: true,
  6561. configurable: true
  6562. });
  6563. Object.defineProperty(Tools, "WarningLogLevel", {
  6564. get: function () {
  6565. return Tools._WarningLogLevel;
  6566. },
  6567. enumerable: true,
  6568. configurable: true
  6569. });
  6570. Object.defineProperty(Tools, "ErrorLogLevel", {
  6571. get: function () {
  6572. return Tools._ErrorLogLevel;
  6573. },
  6574. enumerable: true,
  6575. configurable: true
  6576. });
  6577. Object.defineProperty(Tools, "AllLogLevel", {
  6578. get: function () {
  6579. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6580. },
  6581. enumerable: true,
  6582. configurable: true
  6583. });
  6584. Tools._AddLogEntry = function (entry) {
  6585. Tools._LogCache = entry + Tools._LogCache;
  6586. if (Tools.OnNewCacheEntry) {
  6587. Tools.OnNewCacheEntry(entry);
  6588. }
  6589. };
  6590. Tools._FormatMessage = function (message) {
  6591. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6592. var date = new Date();
  6593. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6594. };
  6595. Tools._LogDisabled = function (message) {
  6596. // nothing to do
  6597. };
  6598. Tools._LogEnabled = function (message) {
  6599. var formattedMessage = Tools._FormatMessage(message);
  6600. console.log("BJS - " + formattedMessage);
  6601. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6602. Tools._AddLogEntry(entry);
  6603. };
  6604. Tools._WarnDisabled = function (message) {
  6605. // nothing to do
  6606. };
  6607. Tools._WarnEnabled = function (message) {
  6608. var formattedMessage = Tools._FormatMessage(message);
  6609. console.warn("BJS - " + formattedMessage);
  6610. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6611. Tools._AddLogEntry(entry);
  6612. };
  6613. Tools._ErrorDisabled = function (message) {
  6614. // nothing to do
  6615. };
  6616. Tools._ErrorEnabled = function (message) {
  6617. Tools.errorsCount++;
  6618. var formattedMessage = Tools._FormatMessage(message);
  6619. console.error("BJS - " + formattedMessage);
  6620. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6621. Tools._AddLogEntry(entry);
  6622. };
  6623. Object.defineProperty(Tools, "LogCache", {
  6624. get: function () {
  6625. return Tools._LogCache;
  6626. },
  6627. enumerable: true,
  6628. configurable: true
  6629. });
  6630. Tools.ClearLogCache = function () {
  6631. Tools._LogCache = "";
  6632. Tools.errorsCount = 0;
  6633. };
  6634. Object.defineProperty(Tools, "LogLevels", {
  6635. set: function (level) {
  6636. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6637. Tools.Log = Tools._LogEnabled;
  6638. }
  6639. else {
  6640. Tools.Log = Tools._LogDisabled;
  6641. }
  6642. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6643. Tools.Warn = Tools._WarnEnabled;
  6644. }
  6645. else {
  6646. Tools.Warn = Tools._WarnDisabled;
  6647. }
  6648. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6649. Tools.Error = Tools._ErrorEnabled;
  6650. }
  6651. else {
  6652. Tools.Error = Tools._ErrorDisabled;
  6653. }
  6654. },
  6655. enumerable: true,
  6656. configurable: true
  6657. });
  6658. Tools.IsWindowObjectExist = function () {
  6659. return (typeof window) !== "undefined";
  6660. };
  6661. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6662. get: function () {
  6663. return Tools._PerformanceNoneLogLevel;
  6664. },
  6665. enumerable: true,
  6666. configurable: true
  6667. });
  6668. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6669. get: function () {
  6670. return Tools._PerformanceUserMarkLogLevel;
  6671. },
  6672. enumerable: true,
  6673. configurable: true
  6674. });
  6675. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6676. get: function () {
  6677. return Tools._PerformanceConsoleLogLevel;
  6678. },
  6679. enumerable: true,
  6680. configurable: true
  6681. });
  6682. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6683. set: function (level) {
  6684. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6685. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6686. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6687. return;
  6688. }
  6689. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6690. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6691. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6692. return;
  6693. }
  6694. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6695. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6696. },
  6697. enumerable: true,
  6698. configurable: true
  6699. });
  6700. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6701. };
  6702. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6703. };
  6704. Tools._StartUserMark = function (counterName, condition) {
  6705. if (condition === void 0) { condition = true; }
  6706. if (!Tools._performance) {
  6707. if (!Tools.IsWindowObjectExist()) {
  6708. return;
  6709. }
  6710. Tools._performance = window.performance;
  6711. }
  6712. if (!condition || !Tools._performance.mark) {
  6713. return;
  6714. }
  6715. Tools._performance.mark(counterName + "-Begin");
  6716. };
  6717. Tools._EndUserMark = function (counterName, condition) {
  6718. if (condition === void 0) { condition = true; }
  6719. if (!condition || !Tools._performance.mark) {
  6720. return;
  6721. }
  6722. Tools._performance.mark(counterName + "-End");
  6723. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6724. };
  6725. Tools._StartPerformanceConsole = function (counterName, condition) {
  6726. if (condition === void 0) { condition = true; }
  6727. if (!condition) {
  6728. return;
  6729. }
  6730. Tools._StartUserMark(counterName, condition);
  6731. if (console.time) {
  6732. console.time(counterName);
  6733. }
  6734. };
  6735. Tools._EndPerformanceConsole = function (counterName, condition) {
  6736. if (condition === void 0) { condition = true; }
  6737. if (!condition) {
  6738. return;
  6739. }
  6740. Tools._EndUserMark(counterName, condition);
  6741. if (console.time) {
  6742. console.timeEnd(counterName);
  6743. }
  6744. };
  6745. Object.defineProperty(Tools, "Now", {
  6746. get: function () {
  6747. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6748. return window.performance.now();
  6749. }
  6750. return new Date().getTime();
  6751. },
  6752. enumerable: true,
  6753. configurable: true
  6754. });
  6755. /**
  6756. * This method will return the name of the class used to create the instance of the given object.
  6757. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6758. * @param object the object to get the class name from
  6759. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6760. */
  6761. Tools.GetClassName = function (object, isType) {
  6762. if (isType === void 0) { isType = false; }
  6763. var name = null;
  6764. if (!isType && object.getClassName) {
  6765. name = object.getClassName();
  6766. }
  6767. else {
  6768. if (object instanceof Object) {
  6769. var classObj = isType ? object : Object.getPrototypeOf(object);
  6770. name = classObj.constructor["__bjsclassName__"];
  6771. }
  6772. if (!name) {
  6773. name = typeof object;
  6774. }
  6775. }
  6776. return name;
  6777. };
  6778. Tools.First = function (array, predicate) {
  6779. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6780. var el = array_1[_i];
  6781. if (predicate(el)) {
  6782. return el;
  6783. }
  6784. }
  6785. return null;
  6786. };
  6787. /**
  6788. * This method will return the name of the full name of the class, including its owning module (if any).
  6789. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  6790. * @param object the object to get the class name from
  6791. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  6792. */
  6793. Tools.getFullClassName = function (object, isType) {
  6794. if (isType === void 0) { isType = false; }
  6795. var className = null;
  6796. var moduleName = null;
  6797. if (!isType && object.getClassName) {
  6798. className = object.getClassName();
  6799. }
  6800. else {
  6801. if (object instanceof Object) {
  6802. var classObj = isType ? object : Object.getPrototypeOf(object);
  6803. className = classObj.constructor["__bjsclassName__"];
  6804. moduleName = classObj.constructor["__bjsmoduleName__"];
  6805. }
  6806. if (!className) {
  6807. className = typeof object;
  6808. }
  6809. }
  6810. if (!className) {
  6811. return null;
  6812. }
  6813. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6814. };
  6815. /**
  6816. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  6817. * @param array
  6818. */
  6819. Tools.arrayOrStringFeeder = function (array) {
  6820. return function (index) {
  6821. if (index >= array.length) {
  6822. return null;
  6823. }
  6824. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6825. if (val && val.getHashCode) {
  6826. val = val.getHashCode();
  6827. }
  6828. if (typeof val === "string") {
  6829. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6830. }
  6831. return val;
  6832. };
  6833. };
  6834. /**
  6835. * Compute the hashCode of a stream of number
  6836. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6837. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6838. * @return the hash code computed
  6839. */
  6840. Tools.hashCodeFromStream = function (feeder) {
  6841. // Based from here: http://stackoverflow.com/a/7616484/802124
  6842. var hash = 0;
  6843. var index = 0;
  6844. var chr = feeder(index++);
  6845. while (chr != null) {
  6846. hash = ((hash << 5) - hash) + chr;
  6847. hash |= 0; // Convert to 32bit integer
  6848. chr = feeder(index++);
  6849. }
  6850. return hash;
  6851. };
  6852. Tools.BaseUrl = "";
  6853. Tools.CorsBehavior = "anonymous";
  6854. Tools.UseFallbackTexture = true;
  6855. /**
  6856. * Use this object to register external classes like custom textures or material
  6857. * to allow the laoders to instantiate them
  6858. */
  6859. Tools.RegisteredExternalClasses = {};
  6860. // Used in case of a texture loading problem
  6861. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  6862. Tools.PreprocessUrl = function (url) {
  6863. return url;
  6864. };
  6865. // Logs
  6866. Tools._NoneLogLevel = 0;
  6867. Tools._MessageLogLevel = 1;
  6868. Tools._WarningLogLevel = 2;
  6869. Tools._ErrorLogLevel = 4;
  6870. Tools._LogCache = "";
  6871. Tools.errorsCount = 0;
  6872. Tools.Log = Tools._LogEnabled;
  6873. Tools.Warn = Tools._WarnEnabled;
  6874. Tools.Error = Tools._ErrorEnabled;
  6875. // Performances
  6876. Tools._PerformanceNoneLogLevel = 0;
  6877. Tools._PerformanceUserMarkLogLevel = 1;
  6878. Tools._PerformanceConsoleLogLevel = 2;
  6879. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6880. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6881. return Tools;
  6882. }());
  6883. BABYLON.Tools = Tools;
  6884. /**
  6885. * This class is used to track a performance counter which is number based.
  6886. * The user has access to many properties which give statistics of different nature
  6887. *
  6888. * The implementer can track two kinds of Performance Counter: time and count
  6889. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  6890. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  6891. */
  6892. var PerfCounter = /** @class */ (function () {
  6893. function PerfCounter() {
  6894. this._startMonitoringTime = 0;
  6895. this._min = 0;
  6896. this._max = 0;
  6897. this._average = 0;
  6898. this._lastSecAverage = 0;
  6899. this._current = 0;
  6900. this._totalValueCount = 0;
  6901. this._totalAccumulated = 0;
  6902. this._lastSecAccumulated = 0;
  6903. this._lastSecTime = 0;
  6904. this._lastSecValueCount = 0;
  6905. }
  6906. Object.defineProperty(PerfCounter.prototype, "min", {
  6907. /**
  6908. * Returns the smallest value ever
  6909. */
  6910. get: function () {
  6911. return this._min;
  6912. },
  6913. enumerable: true,
  6914. configurable: true
  6915. });
  6916. Object.defineProperty(PerfCounter.prototype, "max", {
  6917. /**
  6918. * Returns the biggest value ever
  6919. */
  6920. get: function () {
  6921. return this._max;
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. Object.defineProperty(PerfCounter.prototype, "average", {
  6927. /**
  6928. * Returns the average value since the performance counter is running
  6929. */
  6930. get: function () {
  6931. return this._average;
  6932. },
  6933. enumerable: true,
  6934. configurable: true
  6935. });
  6936. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6937. /**
  6938. * Returns the average value of the last second the counter was monitored
  6939. */
  6940. get: function () {
  6941. return this._lastSecAverage;
  6942. },
  6943. enumerable: true,
  6944. configurable: true
  6945. });
  6946. Object.defineProperty(PerfCounter.prototype, "current", {
  6947. /**
  6948. * Returns the current value
  6949. */
  6950. get: function () {
  6951. return this._current;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(PerfCounter.prototype, "total", {
  6957. get: function () {
  6958. return this._totalAccumulated;
  6959. },
  6960. enumerable: true,
  6961. configurable: true
  6962. });
  6963. Object.defineProperty(PerfCounter.prototype, "count", {
  6964. get: function () {
  6965. return this._totalValueCount;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. /**
  6971. * Call this method to start monitoring a new frame.
  6972. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  6973. */
  6974. PerfCounter.prototype.fetchNewFrame = function () {
  6975. this._totalValueCount++;
  6976. this._current = 0;
  6977. this._lastSecValueCount++;
  6978. };
  6979. /**
  6980. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6981. * @param newCount the count value to add to the monitored count
  6982. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  6983. */
  6984. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6985. if (!PerfCounter.Enabled) {
  6986. return;
  6987. }
  6988. this._current += newCount;
  6989. if (fetchResult) {
  6990. this._fetchResult();
  6991. }
  6992. };
  6993. /**
  6994. * Start monitoring this performance counter
  6995. */
  6996. PerfCounter.prototype.beginMonitoring = function () {
  6997. if (!PerfCounter.Enabled) {
  6998. return;
  6999. }
  7000. this._startMonitoringTime = Tools.Now;
  7001. };
  7002. /**
  7003. * Compute the time lapsed since the previous beginMonitoring() call.
  7004. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  7005. */
  7006. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7007. if (newFrame === void 0) { newFrame = true; }
  7008. if (!PerfCounter.Enabled) {
  7009. return;
  7010. }
  7011. if (newFrame) {
  7012. this.fetchNewFrame();
  7013. }
  7014. var currentTime = Tools.Now;
  7015. this._current = currentTime - this._startMonitoringTime;
  7016. if (newFrame) {
  7017. this._fetchResult();
  7018. }
  7019. };
  7020. PerfCounter.prototype._fetchResult = function () {
  7021. this._totalAccumulated += this._current;
  7022. this._lastSecAccumulated += this._current;
  7023. // Min/Max update
  7024. this._min = Math.min(this._min, this._current);
  7025. this._max = Math.max(this._max, this._current);
  7026. this._average = this._totalAccumulated / this._totalValueCount;
  7027. // Reset last sec?
  7028. var now = Tools.Now;
  7029. if ((now - this._lastSecTime) > 1000) {
  7030. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7031. this._lastSecTime = now;
  7032. this._lastSecAccumulated = 0;
  7033. this._lastSecValueCount = 0;
  7034. }
  7035. };
  7036. PerfCounter.Enabled = true;
  7037. return PerfCounter;
  7038. }());
  7039. BABYLON.PerfCounter = PerfCounter;
  7040. /**
  7041. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7042. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7043. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7044. * @param name The name of the class, case should be preserved
  7045. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7046. */
  7047. function className(name, module) {
  7048. return function (target) {
  7049. target["__bjsclassName__"] = name;
  7050. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7051. };
  7052. }
  7053. BABYLON.className = className;
  7054. /**
  7055. * An implementation of a loop for asynchronous functions.
  7056. */
  7057. var AsyncLoop = /** @class */ (function () {
  7058. /**
  7059. * Constroctor.
  7060. * @param iterations the number of iterations.
  7061. * @param _fn the function to run each iteration
  7062. * @param _successCallback the callback that will be called upon succesful execution
  7063. * @param offset starting offset.
  7064. */
  7065. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7066. if (offset === void 0) { offset = 0; }
  7067. this.iterations = iterations;
  7068. this._fn = _fn;
  7069. this._successCallback = _successCallback;
  7070. this.index = offset - 1;
  7071. this._done = false;
  7072. }
  7073. /**
  7074. * Execute the next iteration. Must be called after the last iteration was finished.
  7075. */
  7076. AsyncLoop.prototype.executeNext = function () {
  7077. if (!this._done) {
  7078. if (this.index + 1 < this.iterations) {
  7079. ++this.index;
  7080. this._fn(this);
  7081. }
  7082. else {
  7083. this.breakLoop();
  7084. }
  7085. }
  7086. };
  7087. /**
  7088. * Break the loop and run the success callback.
  7089. */
  7090. AsyncLoop.prototype.breakLoop = function () {
  7091. this._done = true;
  7092. this._successCallback();
  7093. };
  7094. /**
  7095. * Helper function
  7096. */
  7097. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7098. if (offset === void 0) { offset = 0; }
  7099. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7100. loop.executeNext();
  7101. return loop;
  7102. };
  7103. /**
  7104. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7105. * @param iterations total number of iterations
  7106. * @param syncedIterations number of synchronous iterations in each async iteration.
  7107. * @param fn the function to call each iteration.
  7108. * @param callback a success call back that will be called when iterating stops.
  7109. * @param breakFunction a break condition (optional)
  7110. * @param timeout timeout settings for the setTimeout function. default - 0.
  7111. * @constructor
  7112. */
  7113. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7114. if (timeout === void 0) { timeout = 0; }
  7115. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7116. if (breakFunction && breakFunction())
  7117. loop.breakLoop();
  7118. else {
  7119. setTimeout(function () {
  7120. for (var i = 0; i < syncedIterations; ++i) {
  7121. var iteration = (loop.index * syncedIterations) + i;
  7122. if (iteration >= iterations)
  7123. break;
  7124. fn(iteration);
  7125. if (breakFunction && breakFunction()) {
  7126. loop.breakLoop();
  7127. break;
  7128. }
  7129. }
  7130. loop.executeNext();
  7131. }, timeout);
  7132. }
  7133. }, callback);
  7134. };
  7135. return AsyncLoop;
  7136. }());
  7137. BABYLON.AsyncLoop = AsyncLoop;
  7138. })(BABYLON || (BABYLON = {}));
  7139. //# sourceMappingURL=babylon.tools.js.map
  7140. var BABYLON;
  7141. (function (BABYLON) {
  7142. var Internals;
  7143. (function (Internals) {
  7144. var _AlphaState = /** @class */ (function () {
  7145. /**
  7146. * Initializes the state.
  7147. */
  7148. function _AlphaState() {
  7149. this._isAlphaBlendDirty = false;
  7150. this._isBlendFunctionParametersDirty = false;
  7151. this._isBlendEquationParametersDirty = false;
  7152. this._isBlendConstantsDirty = false;
  7153. this._alphaBlend = false;
  7154. this._blendFunctionParameters = new Array(4);
  7155. this._blendEquationParameters = new Array(2);
  7156. this._blendConstants = new Array(4);
  7157. this.reset();
  7158. }
  7159. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7160. get: function () {
  7161. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7162. },
  7163. enumerable: true,
  7164. configurable: true
  7165. });
  7166. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7167. get: function () {
  7168. return this._alphaBlend;
  7169. },
  7170. set: function (value) {
  7171. if (this._alphaBlend === value) {
  7172. return;
  7173. }
  7174. this._alphaBlend = value;
  7175. this._isAlphaBlendDirty = true;
  7176. },
  7177. enumerable: true,
  7178. configurable: true
  7179. });
  7180. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7181. if (this._blendConstants[0] === r &&
  7182. this._blendConstants[1] === g &&
  7183. this._blendConstants[2] === b &&
  7184. this._blendConstants[3] === a) {
  7185. return;
  7186. }
  7187. this._blendConstants[0] = r;
  7188. this._blendConstants[1] = g;
  7189. this._blendConstants[2] = b;
  7190. this._blendConstants[3] = a;
  7191. this._isBlendConstantsDirty = true;
  7192. };
  7193. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7194. if (this._blendFunctionParameters[0] === value0 &&
  7195. this._blendFunctionParameters[1] === value1 &&
  7196. this._blendFunctionParameters[2] === value2 &&
  7197. this._blendFunctionParameters[3] === value3) {
  7198. return;
  7199. }
  7200. this._blendFunctionParameters[0] = value0;
  7201. this._blendFunctionParameters[1] = value1;
  7202. this._blendFunctionParameters[2] = value2;
  7203. this._blendFunctionParameters[3] = value3;
  7204. this._isBlendFunctionParametersDirty = true;
  7205. };
  7206. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7207. if (this._blendEquationParameters[0] === rgb &&
  7208. this._blendEquationParameters[1] === alpha) {
  7209. return;
  7210. }
  7211. this._blendEquationParameters[0] = rgb;
  7212. this._blendEquationParameters[1] = alpha;
  7213. this._isBlendEquationParametersDirty = true;
  7214. };
  7215. _AlphaState.prototype.reset = function () {
  7216. this._alphaBlend = false;
  7217. this._blendFunctionParameters[0] = null;
  7218. this._blendFunctionParameters[1] = null;
  7219. this._blendFunctionParameters[2] = null;
  7220. this._blendFunctionParameters[3] = null;
  7221. this._blendEquationParameters[0] = null;
  7222. this._blendEquationParameters[1] = null;
  7223. this._blendConstants[0] = null;
  7224. this._blendConstants[1] = null;
  7225. this._blendConstants[2] = null;
  7226. this._blendConstants[3] = null;
  7227. this._isAlphaBlendDirty = true;
  7228. this._isBlendFunctionParametersDirty = false;
  7229. this._isBlendEquationParametersDirty = false;
  7230. this._isBlendConstantsDirty = false;
  7231. };
  7232. _AlphaState.prototype.apply = function (gl) {
  7233. if (!this.isDirty) {
  7234. return;
  7235. }
  7236. // Alpha blend
  7237. if (this._isAlphaBlendDirty) {
  7238. if (this._alphaBlend) {
  7239. gl.enable(gl.BLEND);
  7240. }
  7241. else {
  7242. gl.disable(gl.BLEND);
  7243. }
  7244. this._isAlphaBlendDirty = false;
  7245. }
  7246. // Alpha function
  7247. if (this._isBlendFunctionParametersDirty) {
  7248. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7249. this._isBlendFunctionParametersDirty = false;
  7250. }
  7251. // Alpha equation
  7252. if (this._isBlendEquationParametersDirty) {
  7253. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7254. this._isBlendEquationParametersDirty = false;
  7255. }
  7256. // Constants
  7257. if (this._isBlendConstantsDirty) {
  7258. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7259. this._isBlendConstantsDirty = false;
  7260. }
  7261. };
  7262. return _AlphaState;
  7263. }());
  7264. Internals._AlphaState = _AlphaState;
  7265. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7266. })(BABYLON || (BABYLON = {}));
  7267. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7268. var BABYLON;
  7269. (function (BABYLON) {
  7270. var Internals;
  7271. (function (Internals) {
  7272. var _DepthCullingState = /** @class */ (function () {
  7273. /**
  7274. * Initializes the state.
  7275. */
  7276. function _DepthCullingState() {
  7277. this._isDepthTestDirty = false;
  7278. this._isDepthMaskDirty = false;
  7279. this._isDepthFuncDirty = false;
  7280. this._isCullFaceDirty = false;
  7281. this._isCullDirty = false;
  7282. this._isZOffsetDirty = false;
  7283. this.reset();
  7284. }
  7285. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7286. get: function () {
  7287. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  7288. },
  7289. enumerable: true,
  7290. configurable: true
  7291. });
  7292. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7293. get: function () {
  7294. return this._zOffset;
  7295. },
  7296. set: function (value) {
  7297. if (this._zOffset === value) {
  7298. return;
  7299. }
  7300. this._zOffset = value;
  7301. this._isZOffsetDirty = true;
  7302. },
  7303. enumerable: true,
  7304. configurable: true
  7305. });
  7306. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7307. get: function () {
  7308. return this._cullFace;
  7309. },
  7310. set: function (value) {
  7311. if (this._cullFace === value) {
  7312. return;
  7313. }
  7314. this._cullFace = value;
  7315. this._isCullFaceDirty = true;
  7316. },
  7317. enumerable: true,
  7318. configurable: true
  7319. });
  7320. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7321. get: function () {
  7322. return this._cull;
  7323. },
  7324. set: function (value) {
  7325. if (this._cull === value) {
  7326. return;
  7327. }
  7328. this._cull = value;
  7329. this._isCullDirty = true;
  7330. },
  7331. enumerable: true,
  7332. configurable: true
  7333. });
  7334. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7335. get: function () {
  7336. return this._depthFunc;
  7337. },
  7338. set: function (value) {
  7339. if (this._depthFunc === value) {
  7340. return;
  7341. }
  7342. this._depthFunc = value;
  7343. this._isDepthFuncDirty = true;
  7344. },
  7345. enumerable: true,
  7346. configurable: true
  7347. });
  7348. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7349. get: function () {
  7350. return this._depthMask;
  7351. },
  7352. set: function (value) {
  7353. if (this._depthMask === value) {
  7354. return;
  7355. }
  7356. this._depthMask = value;
  7357. this._isDepthMaskDirty = true;
  7358. },
  7359. enumerable: true,
  7360. configurable: true
  7361. });
  7362. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7363. get: function () {
  7364. return this._depthTest;
  7365. },
  7366. set: function (value) {
  7367. if (this._depthTest === value) {
  7368. return;
  7369. }
  7370. this._depthTest = value;
  7371. this._isDepthTestDirty = true;
  7372. },
  7373. enumerable: true,
  7374. configurable: true
  7375. });
  7376. _DepthCullingState.prototype.reset = function () {
  7377. this._depthMask = true;
  7378. this._depthTest = true;
  7379. this._depthFunc = null;
  7380. this._cullFace = null;
  7381. this._cull = null;
  7382. this._zOffset = 0;
  7383. this._isDepthTestDirty = true;
  7384. this._isDepthMaskDirty = true;
  7385. this._isDepthFuncDirty = false;
  7386. this._isCullFaceDirty = false;
  7387. this._isCullDirty = false;
  7388. this._isZOffsetDirty = false;
  7389. };
  7390. _DepthCullingState.prototype.apply = function (gl) {
  7391. if (!this.isDirty) {
  7392. return;
  7393. }
  7394. // Cull
  7395. if (this._isCullDirty) {
  7396. if (this.cull) {
  7397. gl.enable(gl.CULL_FACE);
  7398. }
  7399. else {
  7400. gl.disable(gl.CULL_FACE);
  7401. }
  7402. this._isCullDirty = false;
  7403. }
  7404. // Cull face
  7405. if (this._isCullFaceDirty) {
  7406. gl.cullFace(this.cullFace);
  7407. this._isCullFaceDirty = false;
  7408. }
  7409. // Depth mask
  7410. if (this._isDepthMaskDirty) {
  7411. gl.depthMask(this.depthMask);
  7412. this._isDepthMaskDirty = false;
  7413. }
  7414. // Depth test
  7415. if (this._isDepthTestDirty) {
  7416. if (this.depthTest) {
  7417. gl.enable(gl.DEPTH_TEST);
  7418. }
  7419. else {
  7420. gl.disable(gl.DEPTH_TEST);
  7421. }
  7422. this._isDepthTestDirty = false;
  7423. }
  7424. // Depth func
  7425. if (this._isDepthFuncDirty) {
  7426. gl.depthFunc(this.depthFunc);
  7427. this._isDepthFuncDirty = false;
  7428. }
  7429. // zOffset
  7430. if (this._isZOffsetDirty) {
  7431. if (this.zOffset) {
  7432. gl.enable(gl.POLYGON_OFFSET_FILL);
  7433. gl.polygonOffset(this.zOffset, 0);
  7434. }
  7435. else {
  7436. gl.disable(gl.POLYGON_OFFSET_FILL);
  7437. }
  7438. this._isZOffsetDirty = false;
  7439. }
  7440. };
  7441. return _DepthCullingState;
  7442. }());
  7443. Internals._DepthCullingState = _DepthCullingState;
  7444. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7445. })(BABYLON || (BABYLON = {}));
  7446. //# sourceMappingURL=babylon.depthCullingState.js.map
  7447. var BABYLON;
  7448. (function (BABYLON) {
  7449. var Internals;
  7450. (function (Internals) {
  7451. var _StencilState = /** @class */ (function () {
  7452. function _StencilState() {
  7453. this._isStencilTestDirty = false;
  7454. this._isStencilMaskDirty = false;
  7455. this._isStencilFuncDirty = false;
  7456. this._isStencilOpDirty = false;
  7457. this.reset();
  7458. }
  7459. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7460. get: function () {
  7461. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7462. },
  7463. enumerable: true,
  7464. configurable: true
  7465. });
  7466. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7467. get: function () {
  7468. return this._stencilFunc;
  7469. },
  7470. set: function (value) {
  7471. if (this._stencilFunc === value) {
  7472. return;
  7473. }
  7474. this._stencilFunc = value;
  7475. this._isStencilFuncDirty = true;
  7476. },
  7477. enumerable: true,
  7478. configurable: true
  7479. });
  7480. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7481. get: function () {
  7482. return this._stencilFuncRef;
  7483. },
  7484. set: function (value) {
  7485. if (this._stencilFuncRef === value) {
  7486. return;
  7487. }
  7488. this._stencilFuncRef = value;
  7489. this._isStencilFuncDirty = true;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7495. get: function () {
  7496. return this._stencilFuncMask;
  7497. },
  7498. set: function (value) {
  7499. if (this._stencilFuncMask === value) {
  7500. return;
  7501. }
  7502. this._stencilFuncMask = value;
  7503. this._isStencilFuncDirty = true;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7509. get: function () {
  7510. return this._stencilOpStencilFail;
  7511. },
  7512. set: function (value) {
  7513. if (this._stencilOpStencilFail === value) {
  7514. return;
  7515. }
  7516. this._stencilOpStencilFail = value;
  7517. this._isStencilOpDirty = true;
  7518. },
  7519. enumerable: true,
  7520. configurable: true
  7521. });
  7522. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7523. get: function () {
  7524. return this._stencilOpDepthFail;
  7525. },
  7526. set: function (value) {
  7527. if (this._stencilOpDepthFail === value) {
  7528. return;
  7529. }
  7530. this._stencilOpDepthFail = value;
  7531. this._isStencilOpDirty = true;
  7532. },
  7533. enumerable: true,
  7534. configurable: true
  7535. });
  7536. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7537. get: function () {
  7538. return this._stencilOpStencilDepthPass;
  7539. },
  7540. set: function (value) {
  7541. if (this._stencilOpStencilDepthPass === value) {
  7542. return;
  7543. }
  7544. this._stencilOpStencilDepthPass = value;
  7545. this._isStencilOpDirty = true;
  7546. },
  7547. enumerable: true,
  7548. configurable: true
  7549. });
  7550. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7551. get: function () {
  7552. return this._stencilMask;
  7553. },
  7554. set: function (value) {
  7555. if (this._stencilMask === value) {
  7556. return;
  7557. }
  7558. this._stencilMask = value;
  7559. this._isStencilMaskDirty = true;
  7560. },
  7561. enumerable: true,
  7562. configurable: true
  7563. });
  7564. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7565. get: function () {
  7566. return this._stencilTest;
  7567. },
  7568. set: function (value) {
  7569. if (this._stencilTest === value) {
  7570. return;
  7571. }
  7572. this._stencilTest = value;
  7573. this._isStencilTestDirty = true;
  7574. },
  7575. enumerable: true,
  7576. configurable: true
  7577. });
  7578. _StencilState.prototype.reset = function () {
  7579. this._stencilTest = false;
  7580. this._stencilMask = 0xFF;
  7581. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7582. this._stencilFuncRef = 1;
  7583. this._stencilFuncMask = 0xFF;
  7584. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7585. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7586. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7587. this._isStencilTestDirty = true;
  7588. this._isStencilMaskDirty = true;
  7589. this._isStencilFuncDirty = true;
  7590. this._isStencilOpDirty = true;
  7591. };
  7592. _StencilState.prototype.apply = function (gl) {
  7593. if (!this.isDirty) {
  7594. return;
  7595. }
  7596. // Stencil test
  7597. if (this._isStencilTestDirty) {
  7598. if (this.stencilTest) {
  7599. gl.enable(gl.STENCIL_TEST);
  7600. }
  7601. else {
  7602. gl.disable(gl.STENCIL_TEST);
  7603. }
  7604. this._isStencilTestDirty = false;
  7605. }
  7606. // Stencil mask
  7607. if (this._isStencilMaskDirty) {
  7608. gl.stencilMask(this.stencilMask);
  7609. this._isStencilMaskDirty = false;
  7610. }
  7611. // Stencil func
  7612. if (this._isStencilFuncDirty) {
  7613. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7614. this._isStencilFuncDirty = false;
  7615. }
  7616. // Stencil op
  7617. if (this._isStencilOpDirty) {
  7618. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7619. this._isStencilOpDirty = false;
  7620. }
  7621. };
  7622. return _StencilState;
  7623. }());
  7624. Internals._StencilState = _StencilState;
  7625. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7626. })(BABYLON || (BABYLON = {}));
  7627. //# sourceMappingURL=babylon.stencilState.js.map
  7628. var BABYLON;
  7629. (function (BABYLON) {
  7630. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7631. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7632. };
  7633. var compileRawShader = function (gl, source, type) {
  7634. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7635. gl.shaderSource(shader, source);
  7636. gl.compileShader(shader);
  7637. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7638. var log = gl.getShaderInfoLog(shader);
  7639. if (log) {
  7640. throw new Error(log);
  7641. }
  7642. }
  7643. if (!shader) {
  7644. throw new Error("Something went wrong while compile the shader.");
  7645. }
  7646. return shader;
  7647. };
  7648. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7649. var magFilter = gl.NEAREST;
  7650. var minFilter = gl.NEAREST;
  7651. switch (samplingMode) {
  7652. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7653. magFilter = gl.LINEAR;
  7654. if (generateMipMaps) {
  7655. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7656. }
  7657. else {
  7658. minFilter = gl.LINEAR;
  7659. }
  7660. break;
  7661. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7662. magFilter = gl.LINEAR;
  7663. if (generateMipMaps) {
  7664. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7665. }
  7666. else {
  7667. minFilter = gl.LINEAR;
  7668. }
  7669. break;
  7670. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7671. magFilter = gl.NEAREST;
  7672. if (generateMipMaps) {
  7673. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7674. }
  7675. else {
  7676. minFilter = gl.NEAREST;
  7677. }
  7678. break;
  7679. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7680. magFilter = gl.NEAREST;
  7681. if (generateMipMaps) {
  7682. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7683. }
  7684. else {
  7685. minFilter = gl.NEAREST;
  7686. }
  7687. break;
  7688. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7689. magFilter = gl.NEAREST;
  7690. if (generateMipMaps) {
  7691. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7692. }
  7693. else {
  7694. minFilter = gl.LINEAR;
  7695. }
  7696. break;
  7697. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7698. magFilter = gl.NEAREST;
  7699. if (generateMipMaps) {
  7700. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7701. }
  7702. else {
  7703. minFilter = gl.LINEAR;
  7704. }
  7705. break;
  7706. case BABYLON.Texture.NEAREST_LINEAR:
  7707. magFilter = gl.NEAREST;
  7708. minFilter = gl.LINEAR;
  7709. break;
  7710. case BABYLON.Texture.NEAREST_NEAREST:
  7711. magFilter = gl.NEAREST;
  7712. minFilter = gl.NEAREST;
  7713. break;
  7714. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7715. magFilter = gl.LINEAR;
  7716. if (generateMipMaps) {
  7717. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7718. }
  7719. else {
  7720. minFilter = gl.NEAREST;
  7721. }
  7722. break;
  7723. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7724. magFilter = gl.LINEAR;
  7725. if (generateMipMaps) {
  7726. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7727. }
  7728. else {
  7729. minFilter = gl.NEAREST;
  7730. }
  7731. break;
  7732. case BABYLON.Texture.LINEAR_LINEAR:
  7733. magFilter = gl.LINEAR;
  7734. minFilter = gl.LINEAR;
  7735. break;
  7736. case BABYLON.Texture.LINEAR_NEAREST:
  7737. magFilter = gl.LINEAR;
  7738. minFilter = gl.NEAREST;
  7739. break;
  7740. }
  7741. return {
  7742. min: minFilter,
  7743. mag: magFilter
  7744. };
  7745. };
  7746. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7747. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7748. var img;
  7749. var onload = function () {
  7750. loadedImages[index] = img;
  7751. loadedImages._internalCount++;
  7752. if (scene) {
  7753. scene._removePendingData(img);
  7754. }
  7755. if (loadedImages._internalCount === 6) {
  7756. onfinish(loadedImages);
  7757. }
  7758. };
  7759. var onerror = function (message, exception) {
  7760. if (scene) {
  7761. scene._removePendingData(img);
  7762. }
  7763. if (onErrorCallBack) {
  7764. onErrorCallBack(message, exception);
  7765. }
  7766. };
  7767. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7768. if (scene) {
  7769. scene._addPendingData(img);
  7770. }
  7771. };
  7772. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7773. if (onError === void 0) { onError = null; }
  7774. var loadedImages = [];
  7775. loadedImages._internalCount = 0;
  7776. for (var index = 0; index < 6; index++) {
  7777. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7778. }
  7779. };
  7780. var BufferPointer = /** @class */ (function () {
  7781. function BufferPointer() {
  7782. }
  7783. return BufferPointer;
  7784. }());
  7785. var InstancingAttributeInfo = /** @class */ (function () {
  7786. function InstancingAttributeInfo() {
  7787. }
  7788. return InstancingAttributeInfo;
  7789. }());
  7790. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7791. /**
  7792. * Define options used to create a render target texture
  7793. */
  7794. var RenderTargetCreationOptions = /** @class */ (function () {
  7795. function RenderTargetCreationOptions() {
  7796. }
  7797. return RenderTargetCreationOptions;
  7798. }());
  7799. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7800. /**
  7801. * Regroup several parameters relative to the browser in use
  7802. */
  7803. var EngineCapabilities = /** @class */ (function () {
  7804. function EngineCapabilities() {
  7805. }
  7806. return EngineCapabilities;
  7807. }());
  7808. BABYLON.EngineCapabilities = EngineCapabilities;
  7809. /**
  7810. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7811. */
  7812. var Engine = /** @class */ (function () {
  7813. /**
  7814. * @constructor
  7815. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7816. * @param {boolean} [antialias] - enable antialias
  7817. * @param options - further options to be sent to the getContext function
  7818. */
  7819. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7820. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7821. var _this = this;
  7822. // Public members
  7823. this.forcePOTTextures = false;
  7824. this.isFullscreen = false;
  7825. this.isPointerLock = false;
  7826. this.cullBackFaces = true;
  7827. this.renderEvenInBackground = true;
  7828. this.preventCacheWipeBetweenFrames = false;
  7829. // To enable/disable IDB support and avoid XHR on .manifest
  7830. this.enableOfflineSupport = false;
  7831. this.scenes = new Array();
  7832. this.postProcesses = new Array();
  7833. // Observables
  7834. /**
  7835. * Observable event triggered each time the rendering canvas is resized
  7836. */
  7837. this.onResizeObservable = new BABYLON.Observable();
  7838. /**
  7839. * Observable event triggered each time the canvas loses focus
  7840. */
  7841. this.onCanvasBlurObservable = new BABYLON.Observable();
  7842. /**
  7843. * Observable event triggered each time the canvas gains focus
  7844. */
  7845. this.onCanvasFocusObservable = new BABYLON.Observable();
  7846. /**
  7847. * Observable event triggered each time the canvas receives pointerout event
  7848. */
  7849. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  7850. /**
  7851. * Observable event triggered before each texture is initialized
  7852. */
  7853. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  7854. //WebVR
  7855. this._vrDisplay = undefined;
  7856. this._vrSupported = false;
  7857. this._vrExclusivePointerMode = false;
  7858. // Uniform buffers list
  7859. this.disableUniformBuffers = false;
  7860. this._uniformBuffers = new Array();
  7861. // Observables
  7862. /**
  7863. * Observable raised when the engine begins a new frame
  7864. */
  7865. this.onBeginFrameObservable = new BABYLON.Observable();
  7866. /**
  7867. * Observable raised when the engine ends the current frame
  7868. */
  7869. this.onEndFrameObservable = new BABYLON.Observable();
  7870. /**
  7871. * Observable raised when the engine is about to compile a shader
  7872. */
  7873. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  7874. /**
  7875. * Observable raised when the engine has jsut compiled a shader
  7876. */
  7877. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  7878. this._windowIsBackground = false;
  7879. this._webGLVersion = 1.0;
  7880. this._badOS = false;
  7881. this._badDesktopOS = false;
  7882. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  7883. this.onVRRequestPresentComplete = new BABYLON.Observable();
  7884. this.onVRRequestPresentStart = new BABYLON.Observable();
  7885. this._colorWrite = true;
  7886. this._drawCalls = new BABYLON.PerfCounter();
  7887. this._renderingQueueLaunched = false;
  7888. this._activeRenderLoops = new Array();
  7889. // Deterministic lockstepMaxSteps
  7890. this._deterministicLockstep = false;
  7891. this._lockstepMaxSteps = 4;
  7892. // Lost context
  7893. this.onContextLostObservable = new BABYLON.Observable();
  7894. this.onContextRestoredObservable = new BABYLON.Observable();
  7895. this._contextWasLost = false;
  7896. this._doNotHandleContextLost = false;
  7897. // FPS
  7898. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7899. this._fps = 60;
  7900. this._deltaTime = 0;
  7901. /**
  7902. * Turn this value on if you want to pause FPS computation when in background
  7903. */
  7904. this.disablePerformanceMonitorInBackground = false;
  7905. // States
  7906. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7907. this._stencilState = new BABYLON.Internals._StencilState();
  7908. this._alphaState = new BABYLON.Internals._AlphaState();
  7909. this._alphaMode = Engine.ALPHA_DISABLE;
  7910. // Cache
  7911. this._internalTexturesCache = new Array();
  7912. this._activeTexturesCache = {};
  7913. this._compiledEffects = {};
  7914. this._vertexAttribArraysEnabled = [];
  7915. this._uintIndicesCurrentlySet = false;
  7916. this._currentBoundBuffer = new Array();
  7917. this._currentBufferPointers = new Array();
  7918. this._currentInstanceLocations = new Array();
  7919. this._currentInstanceBuffers = new Array();
  7920. this._vaoRecordInProgress = false;
  7921. this._mustWipeVertexAttributes = false;
  7922. // Hardware supported Compressed Textures
  7923. this._texturesSupported = new Array();
  7924. this._onVRFullScreenTriggered = function () {
  7925. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  7926. //get the old size before we change
  7927. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7928. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7929. //get the width and height, change the render size
  7930. var leftEye = _this._vrDisplay.getEyeParameters('left');
  7931. _this.setHardwareScalingLevel(1);
  7932. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7933. }
  7934. else {
  7935. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7936. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7937. }
  7938. };
  7939. var canvas = null;
  7940. Engine.Instances.push(this);
  7941. if (!canvasOrContext) {
  7942. return;
  7943. }
  7944. options = options || {};
  7945. if (canvasOrContext.getContext) {
  7946. canvas = canvasOrContext;
  7947. this._renderingCanvas = canvas;
  7948. if (antialias != null) {
  7949. options.antialias = antialias;
  7950. }
  7951. if (options.deterministicLockstep === undefined) {
  7952. options.deterministicLockstep = false;
  7953. }
  7954. if (options.lockstepMaxSteps === undefined) {
  7955. options.lockstepMaxSteps = 4;
  7956. }
  7957. if (options.preserveDrawingBuffer === undefined) {
  7958. options.preserveDrawingBuffer = false;
  7959. }
  7960. if (options.audioEngine === undefined) {
  7961. options.audioEngine = true;
  7962. }
  7963. if (options.stencil === undefined) {
  7964. options.stencil = true;
  7965. }
  7966. this._deterministicLockstep = options.deterministicLockstep;
  7967. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7968. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  7969. // GL
  7970. if (!options.disableWebGL2Support) {
  7971. try {
  7972. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7973. if (this._gl) {
  7974. this._webGLVersion = 2.0;
  7975. }
  7976. }
  7977. catch (e) {
  7978. // Do nothing
  7979. }
  7980. }
  7981. if (!this._gl) {
  7982. if (!canvas) {
  7983. throw new Error("The provided canvas is null or undefined.");
  7984. }
  7985. try {
  7986. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7987. }
  7988. catch (e) {
  7989. throw new Error("WebGL not supported");
  7990. }
  7991. }
  7992. if (!this._gl) {
  7993. throw new Error("WebGL not supported");
  7994. }
  7995. this._onCanvasFocus = function () {
  7996. _this.onCanvasFocusObservable.notifyObservers(_this);
  7997. };
  7998. this._onCanvasBlur = function () {
  7999. _this.onCanvasBlurObservable.notifyObservers(_this);
  8000. };
  8001. canvas.addEventListener("focus", this._onCanvasFocus);
  8002. canvas.addEventListener("blur", this._onCanvasBlur);
  8003. this._onBlur = function () {
  8004. if (_this.disablePerformanceMonitorInBackground) {
  8005. _this._performanceMonitor.disable();
  8006. }
  8007. _this._windowIsBackground = true;
  8008. };
  8009. this._onFocus = function () {
  8010. if (_this.disablePerformanceMonitorInBackground) {
  8011. _this._performanceMonitor.enable();
  8012. }
  8013. _this._windowIsBackground = false;
  8014. };
  8015. this._onCanvasPointerOut = function () {
  8016. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8017. };
  8018. window.addEventListener("blur", this._onBlur);
  8019. window.addEventListener("focus", this._onFocus);
  8020. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8021. // Context lost
  8022. if (!this._doNotHandleContextLost) {
  8023. this._onContextLost = function (evt) {
  8024. evt.preventDefault();
  8025. _this._contextWasLost = true;
  8026. BABYLON.Tools.Warn("WebGL context lost.");
  8027. _this.onContextLostObservable.notifyObservers(_this);
  8028. };
  8029. this._onContextRestored = function (evt) {
  8030. // Adding a timeout to avoid race condition at browser level
  8031. setTimeout(function () {
  8032. // Rebuild gl context
  8033. _this._initGLContext();
  8034. // Rebuild effects
  8035. _this._rebuildEffects();
  8036. // Rebuild textures
  8037. _this._rebuildInternalTextures();
  8038. // Rebuild buffers
  8039. _this._rebuildBuffers();
  8040. // Cache
  8041. _this.wipeCaches(true);
  8042. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8043. _this.onContextRestoredObservable.notifyObservers(_this);
  8044. _this._contextWasLost = false;
  8045. }, 0);
  8046. };
  8047. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8048. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8049. }
  8050. }
  8051. else {
  8052. this._gl = canvasOrContext;
  8053. this._renderingCanvas = this._gl.canvas;
  8054. if (this._gl.renderbufferStorageMultisample) {
  8055. this._webGLVersion = 2.0;
  8056. }
  8057. options.stencil = this._gl.getContextAttributes().stencil;
  8058. }
  8059. // Viewport
  8060. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8061. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8062. this.resize();
  8063. this._isStencilEnable = options.stencil ? true : false;
  8064. this._initGLContext();
  8065. if (canvas) {
  8066. // Fullscreen
  8067. this._onFullscreenChange = function () {
  8068. if (document.fullscreen !== undefined) {
  8069. _this.isFullscreen = document.fullscreen;
  8070. }
  8071. else if (document.mozFullScreen !== undefined) {
  8072. _this.isFullscreen = document.mozFullScreen;
  8073. }
  8074. else if (document.webkitIsFullScreen !== undefined) {
  8075. _this.isFullscreen = document.webkitIsFullScreen;
  8076. }
  8077. else if (document.msIsFullScreen !== undefined) {
  8078. _this.isFullscreen = document.msIsFullScreen;
  8079. }
  8080. // Pointer lock
  8081. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8082. canvas.requestPointerLock = canvas.requestPointerLock ||
  8083. canvas.msRequestPointerLock ||
  8084. canvas.mozRequestPointerLock ||
  8085. canvas.webkitRequestPointerLock;
  8086. if (canvas.requestPointerLock) {
  8087. canvas.requestPointerLock();
  8088. }
  8089. }
  8090. };
  8091. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8092. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8093. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8094. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8095. // Pointer lock
  8096. this._onPointerLockChange = function () {
  8097. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8098. document.webkitPointerLockElement === canvas ||
  8099. document.msPointerLockElement === canvas ||
  8100. document.pointerLockElement === canvas);
  8101. };
  8102. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8103. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8104. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8105. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8106. this._onVRDisplayPointerRestricted = function () {
  8107. if (canvas) {
  8108. canvas.requestPointerLock();
  8109. }
  8110. };
  8111. this._onVRDisplayPointerUnrestricted = function () {
  8112. document.exitPointerLock();
  8113. };
  8114. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8115. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8116. }
  8117. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8118. Engine.audioEngine = new BABYLON.AudioEngine();
  8119. }
  8120. // Prepare buffer pointers
  8121. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8122. this._currentBufferPointers[i] = new BufferPointer();
  8123. }
  8124. // Load WebVR Devices
  8125. if (options.autoEnableWebVR) {
  8126. this.initWebVR();
  8127. }
  8128. // Detect if we are running on a faulty buggy OS.
  8129. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8130. // Detect if we are running on a faulty buggy desktop OS.
  8131. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8132. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8133. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8134. }
  8135. Object.defineProperty(Engine, "LastCreatedEngine", {
  8136. get: function () {
  8137. if (Engine.Instances.length === 0) {
  8138. return null;
  8139. }
  8140. return Engine.Instances[Engine.Instances.length - 1];
  8141. },
  8142. enumerable: true,
  8143. configurable: true
  8144. });
  8145. Object.defineProperty(Engine, "LastCreatedScene", {
  8146. get: function () {
  8147. var lastCreatedEngine = Engine.LastCreatedEngine;
  8148. if (!lastCreatedEngine) {
  8149. return null;
  8150. }
  8151. if (lastCreatedEngine.scenes.length === 0) {
  8152. return null;
  8153. }
  8154. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8155. },
  8156. enumerable: true,
  8157. configurable: true
  8158. });
  8159. /**
  8160. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8161. */
  8162. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8163. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8164. var engine = Engine.Instances[engineIndex];
  8165. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8166. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8167. }
  8168. }
  8169. };
  8170. Object.defineProperty(Engine, "NEVER", {
  8171. get: function () {
  8172. return Engine._NEVER;
  8173. },
  8174. enumerable: true,
  8175. configurable: true
  8176. });
  8177. Object.defineProperty(Engine, "ALWAYS", {
  8178. get: function () {
  8179. return Engine._ALWAYS;
  8180. },
  8181. enumerable: true,
  8182. configurable: true
  8183. });
  8184. Object.defineProperty(Engine, "LESS", {
  8185. get: function () {
  8186. return Engine._LESS;
  8187. },
  8188. enumerable: true,
  8189. configurable: true
  8190. });
  8191. Object.defineProperty(Engine, "EQUAL", {
  8192. get: function () {
  8193. return Engine._EQUAL;
  8194. },
  8195. enumerable: true,
  8196. configurable: true
  8197. });
  8198. Object.defineProperty(Engine, "LEQUAL", {
  8199. get: function () {
  8200. return Engine._LEQUAL;
  8201. },
  8202. enumerable: true,
  8203. configurable: true
  8204. });
  8205. Object.defineProperty(Engine, "GREATER", {
  8206. get: function () {
  8207. return Engine._GREATER;
  8208. },
  8209. enumerable: true,
  8210. configurable: true
  8211. });
  8212. Object.defineProperty(Engine, "GEQUAL", {
  8213. get: function () {
  8214. return Engine._GEQUAL;
  8215. },
  8216. enumerable: true,
  8217. configurable: true
  8218. });
  8219. Object.defineProperty(Engine, "NOTEQUAL", {
  8220. get: function () {
  8221. return Engine._NOTEQUAL;
  8222. },
  8223. enumerable: true,
  8224. configurable: true
  8225. });
  8226. Object.defineProperty(Engine, "KEEP", {
  8227. get: function () {
  8228. return Engine._KEEP;
  8229. },
  8230. enumerable: true,
  8231. configurable: true
  8232. });
  8233. Object.defineProperty(Engine, "REPLACE", {
  8234. get: function () {
  8235. return Engine._REPLACE;
  8236. },
  8237. enumerable: true,
  8238. configurable: true
  8239. });
  8240. Object.defineProperty(Engine, "INCR", {
  8241. get: function () {
  8242. return Engine._INCR;
  8243. },
  8244. enumerable: true,
  8245. configurable: true
  8246. });
  8247. Object.defineProperty(Engine, "DECR", {
  8248. get: function () {
  8249. return Engine._DECR;
  8250. },
  8251. enumerable: true,
  8252. configurable: true
  8253. });
  8254. Object.defineProperty(Engine, "INVERT", {
  8255. get: function () {
  8256. return Engine._INVERT;
  8257. },
  8258. enumerable: true,
  8259. configurable: true
  8260. });
  8261. Object.defineProperty(Engine, "INCR_WRAP", {
  8262. get: function () {
  8263. return Engine._INCR_WRAP;
  8264. },
  8265. enumerable: true,
  8266. configurable: true
  8267. });
  8268. Object.defineProperty(Engine, "DECR_WRAP", {
  8269. get: function () {
  8270. return Engine._DECR_WRAP;
  8271. },
  8272. enumerable: true,
  8273. configurable: true
  8274. });
  8275. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8276. get: function () {
  8277. return Engine._ALPHA_DISABLE;
  8278. },
  8279. enumerable: true,
  8280. configurable: true
  8281. });
  8282. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8283. get: function () {
  8284. return Engine._ALPHA_ONEONE;
  8285. },
  8286. enumerable: true,
  8287. configurable: true
  8288. });
  8289. Object.defineProperty(Engine, "ALPHA_ADD", {
  8290. get: function () {
  8291. return Engine._ALPHA_ADD;
  8292. },
  8293. enumerable: true,
  8294. configurable: true
  8295. });
  8296. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8297. get: function () {
  8298. return Engine._ALPHA_COMBINE;
  8299. },
  8300. enumerable: true,
  8301. configurable: true
  8302. });
  8303. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8304. get: function () {
  8305. return Engine._ALPHA_SUBTRACT;
  8306. },
  8307. enumerable: true,
  8308. configurable: true
  8309. });
  8310. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8311. get: function () {
  8312. return Engine._ALPHA_MULTIPLY;
  8313. },
  8314. enumerable: true,
  8315. configurable: true
  8316. });
  8317. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8318. get: function () {
  8319. return Engine._ALPHA_MAXIMIZED;
  8320. },
  8321. enumerable: true,
  8322. configurable: true
  8323. });
  8324. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8325. get: function () {
  8326. return Engine._ALPHA_PREMULTIPLIED;
  8327. },
  8328. enumerable: true,
  8329. configurable: true
  8330. });
  8331. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8332. get: function () {
  8333. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8339. get: function () {
  8340. return Engine._ALPHA_INTERPOLATE;
  8341. },
  8342. enumerable: true,
  8343. configurable: true
  8344. });
  8345. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8346. get: function () {
  8347. return Engine._ALPHA_SCREENMODE;
  8348. },
  8349. enumerable: true,
  8350. configurable: true
  8351. });
  8352. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8353. get: function () {
  8354. return Engine._DELAYLOADSTATE_NONE;
  8355. },
  8356. enumerable: true,
  8357. configurable: true
  8358. });
  8359. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8360. get: function () {
  8361. return Engine._DELAYLOADSTATE_LOADED;
  8362. },
  8363. enumerable: true,
  8364. configurable: true
  8365. });
  8366. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8367. get: function () {
  8368. return Engine._DELAYLOADSTATE_LOADING;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8374. get: function () {
  8375. return Engine._DELAYLOADSTATE_NOTLOADED;
  8376. },
  8377. enumerable: true,
  8378. configurable: true
  8379. });
  8380. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8381. get: function () {
  8382. return Engine._TEXTUREFORMAT_ALPHA;
  8383. },
  8384. enumerable: true,
  8385. configurable: true
  8386. });
  8387. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8388. get: function () {
  8389. return Engine._TEXTUREFORMAT_LUMINANCE;
  8390. },
  8391. enumerable: true,
  8392. configurable: true
  8393. });
  8394. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8395. get: function () {
  8396. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8402. get: function () {
  8403. return Engine._TEXTUREFORMAT_RGB;
  8404. },
  8405. enumerable: true,
  8406. configurable: true
  8407. });
  8408. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8409. get: function () {
  8410. return Engine._TEXTUREFORMAT_RGBA;
  8411. },
  8412. enumerable: true,
  8413. configurable: true
  8414. });
  8415. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8416. get: function () {
  8417. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8418. },
  8419. enumerable: true,
  8420. configurable: true
  8421. });
  8422. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8423. get: function () {
  8424. return Engine._TEXTURETYPE_FLOAT;
  8425. },
  8426. enumerable: true,
  8427. configurable: true
  8428. });
  8429. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8430. get: function () {
  8431. return Engine._TEXTURETYPE_HALF_FLOAT;
  8432. },
  8433. enumerable: true,
  8434. configurable: true
  8435. });
  8436. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8437. get: function () {
  8438. return Engine._SCALEMODE_FLOOR;
  8439. },
  8440. enumerable: true,
  8441. configurable: true
  8442. });
  8443. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8444. get: function () {
  8445. return Engine._SCALEMODE_NEAREST;
  8446. },
  8447. enumerable: true,
  8448. configurable: true
  8449. });
  8450. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8451. get: function () {
  8452. return Engine._SCALEMODE_CEILING;
  8453. },
  8454. enumerable: true,
  8455. configurable: true
  8456. });
  8457. Object.defineProperty(Engine, "Version", {
  8458. get: function () {
  8459. return "3.1-beta-2";
  8460. },
  8461. enumerable: true,
  8462. configurable: true
  8463. });
  8464. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8465. get: function () {
  8466. return this._vrExclusivePointerMode;
  8467. },
  8468. enumerable: true,
  8469. configurable: true
  8470. });
  8471. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8472. get: function () {
  8473. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8474. },
  8475. enumerable: true,
  8476. configurable: true
  8477. });
  8478. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8479. get: function () {
  8480. return this._webGLVersion < 2 || this.forcePOTTextures;
  8481. },
  8482. enumerable: true,
  8483. configurable: true
  8484. });
  8485. Object.defineProperty(Engine.prototype, "badOS", {
  8486. get: function () {
  8487. return this._badOS;
  8488. },
  8489. enumerable: true,
  8490. configurable: true
  8491. });
  8492. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8493. get: function () {
  8494. return this._badDesktopOS;
  8495. },
  8496. enumerable: true,
  8497. configurable: true
  8498. });
  8499. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8500. get: function () {
  8501. return this._performanceMonitor;
  8502. },
  8503. enumerable: true,
  8504. configurable: true
  8505. });
  8506. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8507. get: function () {
  8508. return this._texturesSupported;
  8509. },
  8510. enumerable: true,
  8511. configurable: true
  8512. });
  8513. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8514. get: function () {
  8515. return this._textureFormatInUse;
  8516. },
  8517. enumerable: true,
  8518. configurable: true
  8519. });
  8520. Object.defineProperty(Engine.prototype, "currentViewport", {
  8521. get: function () {
  8522. return this._cachedViewport;
  8523. },
  8524. enumerable: true,
  8525. configurable: true
  8526. });
  8527. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8528. // Empty texture
  8529. get: function () {
  8530. if (!this._emptyTexture) {
  8531. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8532. }
  8533. return this._emptyTexture;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8539. get: function () {
  8540. if (!this._emptyTexture3D) {
  8541. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8542. }
  8543. return this._emptyTexture3D;
  8544. },
  8545. enumerable: true,
  8546. configurable: true
  8547. });
  8548. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8549. get: function () {
  8550. if (!this._emptyCubeTexture) {
  8551. var faceData = new Uint8Array(4);
  8552. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8553. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8554. }
  8555. return this._emptyCubeTexture;
  8556. },
  8557. enumerable: true,
  8558. configurable: true
  8559. });
  8560. Engine.prototype._rebuildInternalTextures = function () {
  8561. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8562. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8563. var internalTexture = currentState_1[_i];
  8564. internalTexture._rebuild();
  8565. }
  8566. };
  8567. Engine.prototype._rebuildEffects = function () {
  8568. for (var key in this._compiledEffects) {
  8569. var effect = this._compiledEffects[key];
  8570. effect._prepareEffect();
  8571. }
  8572. BABYLON.Effect.ResetCache();
  8573. };
  8574. Engine.prototype._rebuildBuffers = function () {
  8575. // Index / Vertex
  8576. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8577. var scene = _a[_i];
  8578. scene.resetCachedMaterial();
  8579. scene._rebuildGeometries();
  8580. scene._rebuildTextures();
  8581. }
  8582. // Uniforms
  8583. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8584. var uniformBuffer = _c[_b];
  8585. uniformBuffer._rebuild();
  8586. }
  8587. };
  8588. Engine.prototype._initGLContext = function () {
  8589. // Caps
  8590. this._caps = new EngineCapabilities();
  8591. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8592. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8593. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8594. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8595. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8596. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8597. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8598. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8599. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8600. // Infos
  8601. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8602. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8603. if (rendererInfo != null) {
  8604. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8605. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8606. }
  8607. if (!this._glVendor) {
  8608. this._glVendor = "Unknown vendor";
  8609. }
  8610. if (!this._glRenderer) {
  8611. this._glRenderer = "Unknown renderer";
  8612. }
  8613. // Constants
  8614. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8615. if (this._gl.RGBA16F !== 0x881A) {
  8616. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8617. }
  8618. if (this._gl.RGBA32F !== 0x8814) {
  8619. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8620. }
  8621. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8622. this._gl.DEPTH24_STENCIL8 = 35056;
  8623. }
  8624. // Extensions
  8625. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8626. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8627. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8628. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8629. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8630. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8631. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8632. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  8633. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8634. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8635. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8636. this._caps.highPrecisionShaderSupported = true;
  8637. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8638. if (this._caps.timerQuery) {
  8639. if (this._webGLVersion === 1) {
  8640. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8641. }
  8642. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8643. }
  8644. // Checks if some of the format renders first to allow the use of webgl inspector.
  8645. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8646. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8647. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8648. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8649. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8650. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8651. if (this._webGLVersion > 1) {
  8652. this._gl.HALF_FLOAT_OES = 0x140B;
  8653. }
  8654. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8655. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8656. // Draw buffers
  8657. if (this._webGLVersion > 1) {
  8658. this._caps.drawBuffersExtension = true;
  8659. }
  8660. else {
  8661. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8662. if (drawBuffersExtension !== null) {
  8663. this._caps.drawBuffersExtension = true;
  8664. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8665. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8666. for (var i = 0; i < 16; i++) {
  8667. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8668. }
  8669. }
  8670. else {
  8671. this._caps.drawBuffersExtension = false;
  8672. }
  8673. }
  8674. // Depth Texture
  8675. if (this._webGLVersion > 1) {
  8676. this._caps.depthTextureExtension = true;
  8677. }
  8678. else {
  8679. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8680. if (depthTextureExtension != null) {
  8681. this._caps.depthTextureExtension = true;
  8682. }
  8683. }
  8684. // Vertex array object
  8685. if (this._webGLVersion > 1) {
  8686. this._caps.vertexArrayObject = true;
  8687. }
  8688. else {
  8689. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8690. if (vertexArrayObjectExtension != null) {
  8691. this._caps.vertexArrayObject = true;
  8692. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8693. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8694. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8695. }
  8696. else {
  8697. this._caps.vertexArrayObject = false;
  8698. }
  8699. }
  8700. // Instances count
  8701. if (this._webGLVersion > 1) {
  8702. this._caps.instancedArrays = true;
  8703. }
  8704. else {
  8705. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8706. if (instanceExtension != null) {
  8707. this._caps.instancedArrays = true;
  8708. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8709. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8710. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8711. }
  8712. else {
  8713. this._caps.instancedArrays = false;
  8714. }
  8715. }
  8716. // Intelligently add supported compressed formats in order to check for.
  8717. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8718. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8719. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8720. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8721. if (this._caps.astc)
  8722. this.texturesSupported.push('-astc.ktx');
  8723. if (this._caps.s3tc)
  8724. this.texturesSupported.push('-dxt.ktx');
  8725. if (this._caps.pvrtc)
  8726. this.texturesSupported.push('-pvrtc.ktx');
  8727. if (this._caps.etc2)
  8728. this.texturesSupported.push('-etc2.ktx');
  8729. if (this._caps.etc1)
  8730. this.texturesSupported.push('-etc1.ktx');
  8731. if (this._gl.getShaderPrecisionFormat) {
  8732. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8733. if (highp) {
  8734. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8735. }
  8736. }
  8737. // Depth buffer
  8738. this.setDepthBuffer(true);
  8739. this.setDepthFunctionToLessOrEqual();
  8740. this.setDepthWrite(true);
  8741. };
  8742. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8743. get: function () {
  8744. return this._webGLVersion;
  8745. },
  8746. enumerable: true,
  8747. configurable: true
  8748. });
  8749. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8750. /**
  8751. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8752. */
  8753. get: function () {
  8754. return this._isStencilEnable;
  8755. },
  8756. enumerable: true,
  8757. configurable: true
  8758. });
  8759. Engine.prototype._prepareWorkingCanvas = function () {
  8760. if (this._workingCanvas) {
  8761. return;
  8762. }
  8763. this._workingCanvas = document.createElement("canvas");
  8764. var context = this._workingCanvas.getContext("2d");
  8765. if (context) {
  8766. this._workingContext = context;
  8767. }
  8768. };
  8769. Engine.prototype.resetTextureCache = function () {
  8770. for (var key in this._activeTexturesCache) {
  8771. this._activeTexturesCache[key] = null;
  8772. }
  8773. };
  8774. Engine.prototype.isDeterministicLockStep = function () {
  8775. return this._deterministicLockstep;
  8776. };
  8777. Engine.prototype.getLockstepMaxSteps = function () {
  8778. return this._lockstepMaxSteps;
  8779. };
  8780. Engine.prototype.getGlInfo = function () {
  8781. return {
  8782. vendor: this._glVendor,
  8783. renderer: this._glRenderer,
  8784. version: this._glVersion
  8785. };
  8786. };
  8787. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8788. if (useScreen === void 0) { useScreen = false; }
  8789. var viewport = camera.viewport;
  8790. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8791. };
  8792. Engine.prototype.getRenderWidth = function (useScreen) {
  8793. if (useScreen === void 0) { useScreen = false; }
  8794. if (!useScreen && this._currentRenderTarget) {
  8795. return this._currentRenderTarget.width;
  8796. }
  8797. return this._gl.drawingBufferWidth;
  8798. };
  8799. Engine.prototype.getRenderHeight = function (useScreen) {
  8800. if (useScreen === void 0) { useScreen = false; }
  8801. if (!useScreen && this._currentRenderTarget) {
  8802. return this._currentRenderTarget.height;
  8803. }
  8804. return this._gl.drawingBufferHeight;
  8805. };
  8806. Engine.prototype.getRenderingCanvas = function () {
  8807. return this._renderingCanvas;
  8808. };
  8809. Engine.prototype.getRenderingCanvasClientRect = function () {
  8810. if (!this._renderingCanvas) {
  8811. return null;
  8812. }
  8813. return this._renderingCanvas.getBoundingClientRect();
  8814. };
  8815. Engine.prototype.setHardwareScalingLevel = function (level) {
  8816. this._hardwareScalingLevel = level;
  8817. this.resize();
  8818. };
  8819. Engine.prototype.getHardwareScalingLevel = function () {
  8820. return this._hardwareScalingLevel;
  8821. };
  8822. Engine.prototype.getLoadedTexturesCache = function () {
  8823. return this._internalTexturesCache;
  8824. };
  8825. Engine.prototype.getCaps = function () {
  8826. return this._caps;
  8827. };
  8828. Object.defineProperty(Engine.prototype, "drawCalls", {
  8829. /** The number of draw calls submitted last frame */
  8830. get: function () {
  8831. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  8832. return 0;
  8833. },
  8834. enumerable: true,
  8835. configurable: true
  8836. });
  8837. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8838. get: function () {
  8839. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  8840. return null;
  8841. },
  8842. enumerable: true,
  8843. configurable: true
  8844. });
  8845. Engine.prototype.getDepthFunction = function () {
  8846. return this._depthCullingState.depthFunc;
  8847. };
  8848. Engine.prototype.setDepthFunction = function (depthFunc) {
  8849. this._depthCullingState.depthFunc = depthFunc;
  8850. };
  8851. Engine.prototype.setDepthFunctionToGreater = function () {
  8852. this._depthCullingState.depthFunc = this._gl.GREATER;
  8853. };
  8854. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8855. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8856. };
  8857. Engine.prototype.setDepthFunctionToLess = function () {
  8858. this._depthCullingState.depthFunc = this._gl.LESS;
  8859. };
  8860. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8861. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8862. };
  8863. Engine.prototype.getStencilBuffer = function () {
  8864. return this._stencilState.stencilTest;
  8865. };
  8866. Engine.prototype.setStencilBuffer = function (enable) {
  8867. this._stencilState.stencilTest = enable;
  8868. };
  8869. Engine.prototype.getStencilMask = function () {
  8870. return this._stencilState.stencilMask;
  8871. };
  8872. Engine.prototype.setStencilMask = function (mask) {
  8873. this._stencilState.stencilMask = mask;
  8874. };
  8875. Engine.prototype.getStencilFunction = function () {
  8876. return this._stencilState.stencilFunc;
  8877. };
  8878. Engine.prototype.getStencilFunctionReference = function () {
  8879. return this._stencilState.stencilFuncRef;
  8880. };
  8881. Engine.prototype.getStencilFunctionMask = function () {
  8882. return this._stencilState.stencilFuncMask;
  8883. };
  8884. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8885. this._stencilState.stencilFunc = stencilFunc;
  8886. };
  8887. Engine.prototype.setStencilFunctionReference = function (reference) {
  8888. this._stencilState.stencilFuncRef = reference;
  8889. };
  8890. Engine.prototype.setStencilFunctionMask = function (mask) {
  8891. this._stencilState.stencilFuncMask = mask;
  8892. };
  8893. Engine.prototype.getStencilOperationFail = function () {
  8894. return this._stencilState.stencilOpStencilFail;
  8895. };
  8896. Engine.prototype.getStencilOperationDepthFail = function () {
  8897. return this._stencilState.stencilOpDepthFail;
  8898. };
  8899. Engine.prototype.getStencilOperationPass = function () {
  8900. return this._stencilState.stencilOpStencilDepthPass;
  8901. };
  8902. Engine.prototype.setStencilOperationFail = function (operation) {
  8903. this._stencilState.stencilOpStencilFail = operation;
  8904. };
  8905. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8906. this._stencilState.stencilOpDepthFail = operation;
  8907. };
  8908. Engine.prototype.setStencilOperationPass = function (operation) {
  8909. this._stencilState.stencilOpStencilDepthPass = operation;
  8910. };
  8911. Engine.prototype.setDitheringState = function (value) {
  8912. if (value) {
  8913. this._gl.enable(this._gl.DITHER);
  8914. }
  8915. else {
  8916. this._gl.disable(this._gl.DITHER);
  8917. }
  8918. };
  8919. Engine.prototype.setRasterizerState = function (value) {
  8920. if (value) {
  8921. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  8922. }
  8923. else {
  8924. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  8925. }
  8926. };
  8927. /**
  8928. * stop executing a render loop function and remove it from the execution array
  8929. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8930. */
  8931. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8932. if (!renderFunction) {
  8933. this._activeRenderLoops = [];
  8934. return;
  8935. }
  8936. var index = this._activeRenderLoops.indexOf(renderFunction);
  8937. if (index >= 0) {
  8938. this._activeRenderLoops.splice(index, 1);
  8939. }
  8940. };
  8941. Engine.prototype._renderLoop = function () {
  8942. if (!this._contextWasLost) {
  8943. var shouldRender = true;
  8944. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8945. shouldRender = false;
  8946. }
  8947. if (shouldRender) {
  8948. // Start new frame
  8949. this.beginFrame();
  8950. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8951. var renderFunction = this._activeRenderLoops[index];
  8952. renderFunction();
  8953. }
  8954. // Present
  8955. this.endFrame();
  8956. }
  8957. }
  8958. if (this._activeRenderLoops.length > 0) {
  8959. // Register new frame
  8960. var requester = null;
  8961. if (this._vrDisplay && this._vrDisplay.isPresenting)
  8962. requester = this._vrDisplay;
  8963. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  8964. }
  8965. else {
  8966. this._renderingQueueLaunched = false;
  8967. }
  8968. };
  8969. /**
  8970. * Register and execute a render loop. The engine can have more than one render function.
  8971. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8972. * @example
  8973. * engine.runRenderLoop(function () {
  8974. * scene.render()
  8975. * })
  8976. */
  8977. Engine.prototype.runRenderLoop = function (renderFunction) {
  8978. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8979. return;
  8980. }
  8981. this._activeRenderLoops.push(renderFunction);
  8982. if (!this._renderingQueueLaunched) {
  8983. this._renderingQueueLaunched = true;
  8984. this._bindedRenderFunction = this._renderLoop.bind(this);
  8985. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8986. }
  8987. };
  8988. /**
  8989. * Toggle full screen mode.
  8990. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8991. * @param {any} options - an options object to be sent to the requestFullscreen function
  8992. */
  8993. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8994. if (this.isFullscreen) {
  8995. BABYLON.Tools.ExitFullscreen();
  8996. }
  8997. else {
  8998. this._pointerLockRequested = requestPointerLock;
  8999. if (this._renderingCanvas) {
  9000. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9001. }
  9002. }
  9003. };
  9004. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9005. if (stencil === void 0) { stencil = false; }
  9006. this.applyStates();
  9007. var mode = 0;
  9008. if (backBuffer && color) {
  9009. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9010. mode |= this._gl.COLOR_BUFFER_BIT;
  9011. }
  9012. if (depth) {
  9013. this._gl.clearDepth(1.0);
  9014. mode |= this._gl.DEPTH_BUFFER_BIT;
  9015. }
  9016. if (stencil) {
  9017. this._gl.clearStencil(0);
  9018. mode |= this._gl.STENCIL_BUFFER_BIT;
  9019. }
  9020. this._gl.clear(mode);
  9021. };
  9022. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9023. var gl = this._gl;
  9024. // Save state
  9025. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9026. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9027. // Change state
  9028. gl.enable(gl.SCISSOR_TEST);
  9029. gl.scissor(x, y, width, height);
  9030. // Clear
  9031. this.clear(clearColor, true, true, true);
  9032. // Restore state
  9033. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9034. if (curScissor === true) {
  9035. gl.enable(gl.SCISSOR_TEST);
  9036. }
  9037. else {
  9038. gl.disable(gl.SCISSOR_TEST);
  9039. }
  9040. };
  9041. /**
  9042. * Set the WebGL's viewport
  9043. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9044. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9045. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9046. */
  9047. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9048. var width = requiredWidth || this.getRenderWidth();
  9049. var height = requiredHeight || this.getRenderHeight();
  9050. var x = viewport.x || 0;
  9051. var y = viewport.y || 0;
  9052. this._cachedViewport = viewport;
  9053. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9054. };
  9055. /**
  9056. * Directly set the WebGL Viewport
  9057. * The x, y, width & height are directly passed to the WebGL call
  9058. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  9059. */
  9060. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9061. var currentViewport = this._cachedViewport;
  9062. this._cachedViewport = null;
  9063. this._gl.viewport(x, y, width, height);
  9064. return currentViewport;
  9065. };
  9066. Engine.prototype.beginFrame = function () {
  9067. this.onBeginFrameObservable.notifyObservers(this);
  9068. this._measureFps();
  9069. };
  9070. Engine.prototype.endFrame = function () {
  9071. //force a flush in case we are using a bad OS.
  9072. if (this._badOS) {
  9073. this.flushFramebuffer();
  9074. }
  9075. //submit frame to the vr device, if enabled
  9076. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9077. // TODO: We should only submit the frame if we read frameData successfully.
  9078. this._vrDisplay.submitFrame();
  9079. }
  9080. this.onEndFrameObservable.notifyObservers(this);
  9081. };
  9082. /**
  9083. * resize the view according to the canvas' size.
  9084. * @example
  9085. * window.addEventListener("resize", function () {
  9086. * engine.resize();
  9087. * });
  9088. */
  9089. Engine.prototype.resize = function () {
  9090. // We're not resizing the size of the canvas while in VR mode & presenting
  9091. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9092. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9093. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9094. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9095. }
  9096. };
  9097. /**
  9098. * force a specific size of the canvas
  9099. * @param {number} width - the new canvas' width
  9100. * @param {number} height - the new canvas' height
  9101. */
  9102. Engine.prototype.setSize = function (width, height) {
  9103. if (!this._renderingCanvas) {
  9104. return;
  9105. }
  9106. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9107. return;
  9108. }
  9109. this._renderingCanvas.width = width;
  9110. this._renderingCanvas.height = height;
  9111. for (var index = 0; index < this.scenes.length; index++) {
  9112. var scene = this.scenes[index];
  9113. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9114. var cam = scene.cameras[camIndex];
  9115. cam._currentRenderId = 0;
  9116. }
  9117. }
  9118. if (this.onResizeObservable.hasObservers) {
  9119. this.onResizeObservable.notifyObservers(this);
  9120. }
  9121. };
  9122. // WebVR functions
  9123. Engine.prototype.isVRDevicePresent = function () {
  9124. return !!this._vrDisplay;
  9125. };
  9126. Engine.prototype.getVRDevice = function () {
  9127. return this._vrDisplay;
  9128. };
  9129. Engine.prototype.initWebVR = function () {
  9130. var _this = this;
  9131. var notifyObservers = function () {
  9132. var eventArgs = {
  9133. vrDisplay: _this._vrDisplay,
  9134. vrSupported: _this._vrSupported
  9135. };
  9136. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9137. };
  9138. if (!this._onVrDisplayConnect) {
  9139. this._onVrDisplayConnect = function (event) {
  9140. _this._vrDisplay = event.display;
  9141. notifyObservers();
  9142. };
  9143. this._onVrDisplayDisconnect = function () {
  9144. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9145. _this._vrDisplay = undefined;
  9146. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9147. notifyObservers();
  9148. };
  9149. this._onVrDisplayPresentChange = function () {
  9150. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9151. };
  9152. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9153. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9154. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9155. }
  9156. this._getVRDisplays(notifyObservers);
  9157. return this.onVRDisplayChangedObservable;
  9158. };
  9159. Engine.prototype.enableVR = function () {
  9160. var _this = this;
  9161. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9162. var onResolved = function () {
  9163. _this.onVRRequestPresentComplete.notifyObservers(true);
  9164. _this._onVRFullScreenTriggered();
  9165. };
  9166. var onRejected = function () {
  9167. _this.onVRRequestPresentComplete.notifyObservers(false);
  9168. };
  9169. this.onVRRequestPresentStart.notifyObservers(this);
  9170. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9171. }
  9172. };
  9173. Engine.prototype.disableVR = function () {
  9174. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9175. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9176. }
  9177. };
  9178. Engine.prototype._getVRDisplays = function (callback) {
  9179. var _this = this;
  9180. var getWebVRDevices = function (devices) {
  9181. _this._vrSupported = true;
  9182. // note that devices may actually be an empty array. This is fine;
  9183. // we expect this._vrDisplay to be undefined in this case.
  9184. return _this._vrDisplay = devices[0];
  9185. };
  9186. if (navigator.getVRDisplays) {
  9187. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9188. // TODO: System CANNOT support WebVR, despite API presence.
  9189. _this._vrSupported = false;
  9190. callback();
  9191. });
  9192. }
  9193. else {
  9194. // TODO: Browser does not support WebVR
  9195. this._vrDisplay = undefined;
  9196. this._vrSupported = false;
  9197. callback();
  9198. }
  9199. };
  9200. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9201. if (this._currentRenderTarget) {
  9202. this.unBindFramebuffer(this._currentRenderTarget);
  9203. }
  9204. this._currentRenderTarget = texture;
  9205. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9206. var gl = this._gl;
  9207. if (texture.isCube) {
  9208. if (faceIndex === undefined) {
  9209. faceIndex = 0;
  9210. }
  9211. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9212. }
  9213. if (this._cachedViewport && !forceFullscreenViewport) {
  9214. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9215. }
  9216. else {
  9217. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9218. }
  9219. this.wipeCaches();
  9220. };
  9221. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9222. if (this._currentFramebuffer !== framebuffer) {
  9223. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9224. this._currentFramebuffer = framebuffer;
  9225. }
  9226. };
  9227. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9228. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9229. this._currentRenderTarget = null;
  9230. // If MSAA, we need to bitblt back to main texture
  9231. var gl = this._gl;
  9232. if (texture._MSAAFramebuffer) {
  9233. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9234. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9235. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9236. }
  9237. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9238. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9239. gl.generateMipmap(gl.TEXTURE_2D);
  9240. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9241. }
  9242. if (onBeforeUnbind) {
  9243. if (texture._MSAAFramebuffer) {
  9244. // Bind the correct framebuffer
  9245. this.bindUnboundFramebuffer(texture._framebuffer);
  9246. }
  9247. onBeforeUnbind();
  9248. }
  9249. this.bindUnboundFramebuffer(null);
  9250. };
  9251. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9252. if (texture.generateMipMaps) {
  9253. var gl = this._gl;
  9254. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9255. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9256. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9257. }
  9258. };
  9259. Engine.prototype.flushFramebuffer = function () {
  9260. this._gl.flush();
  9261. };
  9262. Engine.prototype.restoreDefaultFramebuffer = function () {
  9263. if (this._currentRenderTarget) {
  9264. this.unBindFramebuffer(this._currentRenderTarget);
  9265. }
  9266. else {
  9267. this.bindUnboundFramebuffer(null);
  9268. }
  9269. if (this._cachedViewport) {
  9270. this.setViewport(this._cachedViewport);
  9271. }
  9272. this.wipeCaches();
  9273. };
  9274. // UBOs
  9275. Engine.prototype.createUniformBuffer = function (elements) {
  9276. var ubo = this._gl.createBuffer();
  9277. if (!ubo) {
  9278. throw new Error("Unable to create uniform buffer");
  9279. }
  9280. this.bindUniformBuffer(ubo);
  9281. if (elements instanceof Float32Array) {
  9282. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9283. }
  9284. else {
  9285. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9286. }
  9287. this.bindUniformBuffer(null);
  9288. ubo.references = 1;
  9289. return ubo;
  9290. };
  9291. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9292. var ubo = this._gl.createBuffer();
  9293. if (!ubo) {
  9294. throw new Error("Unable to create dynamic uniform buffer");
  9295. }
  9296. this.bindUniformBuffer(ubo);
  9297. if (elements instanceof Float32Array) {
  9298. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9299. }
  9300. else {
  9301. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9302. }
  9303. this.bindUniformBuffer(null);
  9304. ubo.references = 1;
  9305. return ubo;
  9306. };
  9307. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9308. this.bindUniformBuffer(uniformBuffer);
  9309. if (offset === undefined) {
  9310. offset = 0;
  9311. }
  9312. if (count === undefined) {
  9313. if (elements instanceof Float32Array) {
  9314. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9315. }
  9316. else {
  9317. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9318. }
  9319. }
  9320. else {
  9321. if (elements instanceof Float32Array) {
  9322. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9323. }
  9324. else {
  9325. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9326. }
  9327. }
  9328. this.bindUniformBuffer(null);
  9329. };
  9330. // VBOs
  9331. Engine.prototype._resetVertexBufferBinding = function () {
  9332. this.bindArrayBuffer(null);
  9333. this._cachedVertexBuffers = null;
  9334. };
  9335. Engine.prototype.createVertexBuffer = function (vertices) {
  9336. var vbo = this._gl.createBuffer();
  9337. if (!vbo) {
  9338. throw new Error("Unable to create vertex buffer");
  9339. }
  9340. this.bindArrayBuffer(vbo);
  9341. if (vertices instanceof Float32Array) {
  9342. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9343. }
  9344. else {
  9345. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9346. }
  9347. this._resetVertexBufferBinding();
  9348. vbo.references = 1;
  9349. return vbo;
  9350. };
  9351. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9352. var vbo = this._gl.createBuffer();
  9353. if (!vbo) {
  9354. throw new Error("Unable to create dynamic vertex buffer");
  9355. }
  9356. this.bindArrayBuffer(vbo);
  9357. if (vertices instanceof Float32Array) {
  9358. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9359. }
  9360. else {
  9361. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9362. }
  9363. this._resetVertexBufferBinding();
  9364. vbo.references = 1;
  9365. return vbo;
  9366. };
  9367. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9368. if (offset === void 0) { offset = 0; }
  9369. // Force cache update
  9370. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9371. this.bindIndexBuffer(indexBuffer);
  9372. var arrayBuffer;
  9373. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9374. arrayBuffer = indices;
  9375. }
  9376. else {
  9377. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9378. }
  9379. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9380. this._resetIndexBufferBinding();
  9381. };
  9382. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9383. this.bindArrayBuffer(vertexBuffer);
  9384. if (offset === undefined) {
  9385. offset = 0;
  9386. }
  9387. if (count === undefined) {
  9388. if (vertices instanceof Float32Array) {
  9389. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9390. }
  9391. else {
  9392. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9393. }
  9394. }
  9395. else {
  9396. if (vertices instanceof Float32Array) {
  9397. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9398. }
  9399. else {
  9400. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9401. }
  9402. }
  9403. this._resetVertexBufferBinding();
  9404. };
  9405. Engine.prototype._resetIndexBufferBinding = function () {
  9406. this.bindIndexBuffer(null);
  9407. this._cachedIndexBuffer = null;
  9408. };
  9409. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9410. var vbo = this._gl.createBuffer();
  9411. if (!vbo) {
  9412. throw new Error("Unable to create index buffer");
  9413. }
  9414. this.bindIndexBuffer(vbo);
  9415. // Check for 32 bits indices
  9416. var arrayBuffer;
  9417. var need32Bits = false;
  9418. if (indices instanceof Uint16Array) {
  9419. arrayBuffer = indices;
  9420. }
  9421. else {
  9422. //check 32 bit support
  9423. if (this._caps.uintIndices) {
  9424. if (indices instanceof Uint32Array) {
  9425. arrayBuffer = indices;
  9426. need32Bits = true;
  9427. }
  9428. else {
  9429. //number[] or Int32Array, check if 32 bit is necessary
  9430. for (var index = 0; index < indices.length; index++) {
  9431. if (indices[index] > 65535) {
  9432. need32Bits = true;
  9433. break;
  9434. }
  9435. }
  9436. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9437. }
  9438. }
  9439. else {
  9440. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9441. arrayBuffer = new Uint16Array(indices);
  9442. }
  9443. }
  9444. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9445. this._resetIndexBufferBinding();
  9446. vbo.references = 1;
  9447. vbo.is32Bits = need32Bits;
  9448. return vbo;
  9449. };
  9450. Engine.prototype.bindArrayBuffer = function (buffer) {
  9451. if (!this._vaoRecordInProgress) {
  9452. this._unbindVertexArrayObject();
  9453. }
  9454. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9455. };
  9456. Engine.prototype.bindUniformBuffer = function (buffer) {
  9457. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9458. };
  9459. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9460. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9461. };
  9462. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9463. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9464. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9465. };
  9466. ;
  9467. Engine.prototype.bindIndexBuffer = function (buffer) {
  9468. if (!this._vaoRecordInProgress) {
  9469. this._unbindVertexArrayObject();
  9470. }
  9471. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9472. };
  9473. Engine.prototype.bindBuffer = function (buffer, target) {
  9474. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9475. this._gl.bindBuffer(target, buffer);
  9476. this._currentBoundBuffer[target] = buffer;
  9477. }
  9478. };
  9479. Engine.prototype.updateArrayBuffer = function (data) {
  9480. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9481. };
  9482. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9483. var pointer = this._currentBufferPointers[indx];
  9484. var changed = false;
  9485. if (!pointer.active) {
  9486. changed = true;
  9487. pointer.active = true;
  9488. pointer.index = indx;
  9489. pointer.size = size;
  9490. pointer.type = type;
  9491. pointer.normalized = normalized;
  9492. pointer.stride = stride;
  9493. pointer.offset = offset;
  9494. pointer.buffer = buffer;
  9495. }
  9496. else {
  9497. if (pointer.buffer !== buffer) {
  9498. pointer.buffer = buffer;
  9499. changed = true;
  9500. }
  9501. if (pointer.size !== size) {
  9502. pointer.size = size;
  9503. changed = true;
  9504. }
  9505. if (pointer.type !== type) {
  9506. pointer.type = type;
  9507. changed = true;
  9508. }
  9509. if (pointer.normalized !== normalized) {
  9510. pointer.normalized = normalized;
  9511. changed = true;
  9512. }
  9513. if (pointer.stride !== stride) {
  9514. pointer.stride = stride;
  9515. changed = true;
  9516. }
  9517. if (pointer.offset !== offset) {
  9518. pointer.offset = offset;
  9519. changed = true;
  9520. }
  9521. }
  9522. if (changed || this._vaoRecordInProgress) {
  9523. this.bindArrayBuffer(buffer);
  9524. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9525. }
  9526. };
  9527. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9528. if (indexBuffer == null) {
  9529. return;
  9530. }
  9531. if (this._cachedIndexBuffer !== indexBuffer) {
  9532. this._cachedIndexBuffer = indexBuffer;
  9533. this.bindIndexBuffer(indexBuffer);
  9534. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9535. }
  9536. };
  9537. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9538. var attributes = effect.getAttributesNames();
  9539. if (!this._vaoRecordInProgress) {
  9540. this._unbindVertexArrayObject();
  9541. }
  9542. this.unbindAllAttributes();
  9543. for (var index = 0; index < attributes.length; index++) {
  9544. var order = effect.getAttributeLocation(index);
  9545. if (order >= 0) {
  9546. var vertexBuffer = vertexBuffers[attributes[index]];
  9547. if (!vertexBuffer) {
  9548. continue;
  9549. }
  9550. this._gl.enableVertexAttribArray(order);
  9551. if (!this._vaoRecordInProgress) {
  9552. this._vertexAttribArraysEnabled[order] = true;
  9553. }
  9554. var buffer = vertexBuffer.getBuffer();
  9555. if (buffer) {
  9556. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9557. if (vertexBuffer.getIsInstanced()) {
  9558. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9559. if (!this._vaoRecordInProgress) {
  9560. this._currentInstanceLocations.push(order);
  9561. this._currentInstanceBuffers.push(buffer);
  9562. }
  9563. }
  9564. }
  9565. }
  9566. }
  9567. };
  9568. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9569. var vao = this._gl.createVertexArray();
  9570. this._vaoRecordInProgress = true;
  9571. this._gl.bindVertexArray(vao);
  9572. this._mustWipeVertexAttributes = true;
  9573. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9574. this.bindIndexBuffer(indexBuffer);
  9575. this._vaoRecordInProgress = false;
  9576. this._gl.bindVertexArray(null);
  9577. return vao;
  9578. };
  9579. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9580. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9581. this._cachedVertexArrayObject = vertexArrayObject;
  9582. this._gl.bindVertexArray(vertexArrayObject);
  9583. this._cachedVertexBuffers = null;
  9584. this._cachedIndexBuffer = null;
  9585. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9586. this._mustWipeVertexAttributes = true;
  9587. }
  9588. };
  9589. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9590. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9591. this._cachedVertexBuffers = vertexBuffer;
  9592. this._cachedEffectForVertexBuffers = effect;
  9593. var attributesCount = effect.getAttributesCount();
  9594. this._unbindVertexArrayObject();
  9595. this.unbindAllAttributes();
  9596. var offset = 0;
  9597. for (var index = 0; index < attributesCount; index++) {
  9598. if (index < vertexDeclaration.length) {
  9599. var order = effect.getAttributeLocation(index);
  9600. if (order >= 0) {
  9601. this._gl.enableVertexAttribArray(order);
  9602. this._vertexAttribArraysEnabled[order] = true;
  9603. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9604. }
  9605. offset += vertexDeclaration[index] * 4;
  9606. }
  9607. }
  9608. }
  9609. this._bindIndexBufferWithCache(indexBuffer);
  9610. };
  9611. Engine.prototype._unbindVertexArrayObject = function () {
  9612. if (!this._cachedVertexArrayObject) {
  9613. return;
  9614. }
  9615. this._cachedVertexArrayObject = null;
  9616. this._gl.bindVertexArray(null);
  9617. };
  9618. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9619. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9620. this._cachedVertexBuffers = vertexBuffers;
  9621. this._cachedEffectForVertexBuffers = effect;
  9622. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9623. }
  9624. this._bindIndexBufferWithCache(indexBuffer);
  9625. };
  9626. Engine.prototype.unbindInstanceAttributes = function () {
  9627. var boundBuffer;
  9628. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9629. var instancesBuffer = this._currentInstanceBuffers[i];
  9630. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9631. boundBuffer = instancesBuffer;
  9632. this.bindArrayBuffer(instancesBuffer);
  9633. }
  9634. var offsetLocation = this._currentInstanceLocations[i];
  9635. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9636. }
  9637. this._currentInstanceBuffers.length = 0;
  9638. this._currentInstanceLocations.length = 0;
  9639. };
  9640. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9641. this._gl.deleteVertexArray(vao);
  9642. };
  9643. Engine.prototype._releaseBuffer = function (buffer) {
  9644. buffer.references--;
  9645. if (buffer.references === 0) {
  9646. this._gl.deleteBuffer(buffer);
  9647. return true;
  9648. }
  9649. return false;
  9650. };
  9651. Engine.prototype.createInstancesBuffer = function (capacity) {
  9652. var buffer = this._gl.createBuffer();
  9653. if (!buffer) {
  9654. throw new Error("Unable to create instance buffer");
  9655. }
  9656. buffer.capacity = capacity;
  9657. this.bindArrayBuffer(buffer);
  9658. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9659. return buffer;
  9660. };
  9661. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9662. this._gl.deleteBuffer(buffer);
  9663. };
  9664. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9665. this.bindArrayBuffer(instancesBuffer);
  9666. if (data) {
  9667. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9668. }
  9669. if (offsetLocations[0].index !== undefined) {
  9670. var stride = 0;
  9671. for (var i = 0; i < offsetLocations.length; i++) {
  9672. var ai = offsetLocations[i];
  9673. stride += ai.attributeSize * 4;
  9674. }
  9675. for (var i = 0; i < offsetLocations.length; i++) {
  9676. var ai = offsetLocations[i];
  9677. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9678. this._gl.enableVertexAttribArray(ai.index);
  9679. this._vertexAttribArraysEnabled[ai.index] = true;
  9680. }
  9681. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9682. this._gl.vertexAttribDivisor(ai.index, 1);
  9683. this._currentInstanceLocations.push(ai.index);
  9684. this._currentInstanceBuffers.push(instancesBuffer);
  9685. }
  9686. }
  9687. else {
  9688. for (var index = 0; index < 4; index++) {
  9689. var offsetLocation = offsetLocations[index];
  9690. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9691. this._gl.enableVertexAttribArray(offsetLocation);
  9692. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9693. }
  9694. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9695. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9696. this._currentInstanceLocations.push(offsetLocation);
  9697. this._currentInstanceBuffers.push(instancesBuffer);
  9698. }
  9699. }
  9700. };
  9701. Engine.prototype.applyStates = function () {
  9702. this._depthCullingState.apply(this._gl);
  9703. this._stencilState.apply(this._gl);
  9704. this._alphaState.apply(this._gl);
  9705. };
  9706. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9707. // Apply states
  9708. this.applyStates();
  9709. this._drawCalls.addCount(1, false);
  9710. // Render
  9711. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9712. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9713. if (instancesCount) {
  9714. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9715. return;
  9716. }
  9717. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9718. };
  9719. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9720. // Apply states
  9721. this.applyStates();
  9722. this._drawCalls.addCount(1, false);
  9723. if (instancesCount) {
  9724. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9725. return;
  9726. }
  9727. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9728. };
  9729. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9730. // Apply states
  9731. this.applyStates();
  9732. this._drawCalls.addCount(1, false);
  9733. if (instancesCount) {
  9734. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9735. return;
  9736. }
  9737. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9738. };
  9739. // Shaders
  9740. Engine.prototype._releaseEffect = function (effect) {
  9741. if (this._compiledEffects[effect._key]) {
  9742. delete this._compiledEffects[effect._key];
  9743. this._deleteProgram(effect.getProgram());
  9744. }
  9745. };
  9746. Engine.prototype._deleteProgram = function (program) {
  9747. if (program) {
  9748. program.__SPECTOR_rebuildProgram = null;
  9749. if (program.transformFeedback) {
  9750. this.deleteTransformFeedback(program.transformFeedback);
  9751. program.transformFeedback = null;
  9752. }
  9753. this._gl.deleteProgram(program);
  9754. }
  9755. };
  9756. /**
  9757. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9758. * @param samplers An array of string used to represent textures
  9759. */
  9760. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9761. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9762. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9763. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9764. if (this._compiledEffects[name]) {
  9765. var compiledEffect = this._compiledEffects[name];
  9766. if (onCompiled && compiledEffect.isReady()) {
  9767. onCompiled(compiledEffect);
  9768. }
  9769. return compiledEffect;
  9770. }
  9771. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9772. effect._key = name;
  9773. this._compiledEffects[name] = effect;
  9774. return effect;
  9775. };
  9776. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9777. if (uniformsNames === void 0) { uniformsNames = []; }
  9778. if (samplers === void 0) { samplers = []; }
  9779. if (defines === void 0) { defines = ""; }
  9780. return this.createEffect({
  9781. vertex: "particles",
  9782. fragmentElement: fragmentName
  9783. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9784. };
  9785. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  9786. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9787. context = context || this._gl;
  9788. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  9789. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  9790. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9791. };
  9792. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  9793. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9794. context = context || this._gl;
  9795. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  9796. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9797. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9798. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9799. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  9800. this.onAfterShaderCompilationObservable.notifyObservers(this);
  9801. return program;
  9802. };
  9803. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  9804. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  9805. var shaderProgram = context.createProgram();
  9806. if (!shaderProgram) {
  9807. throw new Error("Unable to create program");
  9808. }
  9809. context.attachShader(shaderProgram, vertexShader);
  9810. context.attachShader(shaderProgram, fragmentShader);
  9811. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9812. var transformFeedback = this.createTransformFeedback();
  9813. this.bindTransformFeedback(transformFeedback);
  9814. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  9815. shaderProgram.transformFeedback = transformFeedback;
  9816. }
  9817. context.linkProgram(shaderProgram);
  9818. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  9819. this.bindTransformFeedback(null);
  9820. }
  9821. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9822. if (!linked) {
  9823. context.validateProgram(shaderProgram);
  9824. var error = context.getProgramInfoLog(shaderProgram);
  9825. if (error) {
  9826. throw new Error(error);
  9827. }
  9828. }
  9829. context.deleteShader(vertexShader);
  9830. context.deleteShader(fragmentShader);
  9831. return shaderProgram;
  9832. };
  9833. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9834. var results = new Array();
  9835. for (var index = 0; index < uniformsNames.length; index++) {
  9836. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9837. }
  9838. return results;
  9839. };
  9840. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9841. var results = [];
  9842. for (var index = 0; index < attributesNames.length; index++) {
  9843. try {
  9844. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9845. }
  9846. catch (e) {
  9847. results.push(-1);
  9848. }
  9849. }
  9850. return results;
  9851. };
  9852. Engine.prototype.enableEffect = function (effect) {
  9853. if (!effect) {
  9854. return;
  9855. }
  9856. // Use program
  9857. this.setProgram(effect.getProgram());
  9858. this._currentEffect = effect;
  9859. if (effect.onBind) {
  9860. effect.onBind(effect);
  9861. }
  9862. effect.onBindObservable.notifyObservers(effect);
  9863. };
  9864. Engine.prototype.setIntArray = function (uniform, array) {
  9865. if (!uniform)
  9866. return;
  9867. this._gl.uniform1iv(uniform, array);
  9868. };
  9869. Engine.prototype.setIntArray2 = function (uniform, array) {
  9870. if (!uniform || array.length % 2 !== 0)
  9871. return;
  9872. this._gl.uniform2iv(uniform, array);
  9873. };
  9874. Engine.prototype.setIntArray3 = function (uniform, array) {
  9875. if (!uniform || array.length % 3 !== 0)
  9876. return;
  9877. this._gl.uniform3iv(uniform, array);
  9878. };
  9879. Engine.prototype.setIntArray4 = function (uniform, array) {
  9880. if (!uniform || array.length % 4 !== 0)
  9881. return;
  9882. this._gl.uniform4iv(uniform, array);
  9883. };
  9884. Engine.prototype.setFloatArray = function (uniform, array) {
  9885. if (!uniform)
  9886. return;
  9887. this._gl.uniform1fv(uniform, array);
  9888. };
  9889. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9890. if (!uniform || array.length % 2 !== 0)
  9891. return;
  9892. this._gl.uniform2fv(uniform, array);
  9893. };
  9894. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9895. if (!uniform || array.length % 3 !== 0)
  9896. return;
  9897. this._gl.uniform3fv(uniform, array);
  9898. };
  9899. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9900. if (!uniform || array.length % 4 !== 0)
  9901. return;
  9902. this._gl.uniform4fv(uniform, array);
  9903. };
  9904. Engine.prototype.setArray = function (uniform, array) {
  9905. if (!uniform)
  9906. return;
  9907. this._gl.uniform1fv(uniform, array);
  9908. };
  9909. Engine.prototype.setArray2 = function (uniform, array) {
  9910. if (!uniform || array.length % 2 !== 0)
  9911. return;
  9912. this._gl.uniform2fv(uniform, array);
  9913. };
  9914. Engine.prototype.setArray3 = function (uniform, array) {
  9915. if (!uniform || array.length % 3 !== 0)
  9916. return;
  9917. this._gl.uniform3fv(uniform, array);
  9918. };
  9919. Engine.prototype.setArray4 = function (uniform, array) {
  9920. if (!uniform || array.length % 4 !== 0)
  9921. return;
  9922. this._gl.uniform4fv(uniform, array);
  9923. };
  9924. Engine.prototype.setMatrices = function (uniform, matrices) {
  9925. if (!uniform)
  9926. return;
  9927. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9928. };
  9929. Engine.prototype.setMatrix = function (uniform, matrix) {
  9930. if (!uniform)
  9931. return;
  9932. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9933. };
  9934. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9935. if (!uniform)
  9936. return;
  9937. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9938. };
  9939. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9940. if (!uniform)
  9941. return;
  9942. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9943. };
  9944. Engine.prototype.setFloat = function (uniform, value) {
  9945. if (!uniform)
  9946. return;
  9947. this._gl.uniform1f(uniform, value);
  9948. };
  9949. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9950. if (!uniform)
  9951. return;
  9952. this._gl.uniform2f(uniform, x, y);
  9953. };
  9954. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9955. if (!uniform)
  9956. return;
  9957. this._gl.uniform3f(uniform, x, y, z);
  9958. };
  9959. Engine.prototype.setBool = function (uniform, bool) {
  9960. if (!uniform)
  9961. return;
  9962. this._gl.uniform1i(uniform, bool);
  9963. };
  9964. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9965. if (!uniform)
  9966. return;
  9967. this._gl.uniform4f(uniform, x, y, z, w);
  9968. };
  9969. Engine.prototype.setColor3 = function (uniform, color3) {
  9970. if (!uniform)
  9971. return;
  9972. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9973. };
  9974. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9975. if (!uniform)
  9976. return;
  9977. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9978. };
  9979. // States
  9980. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9981. if (zOffset === void 0) { zOffset = 0; }
  9982. if (reverseSide === void 0) { reverseSide = false; }
  9983. // Culling
  9984. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9985. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9986. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9987. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9988. if (culling) {
  9989. this._depthCullingState.cullFace = cullFace;
  9990. this._depthCullingState.cull = true;
  9991. }
  9992. else {
  9993. this._depthCullingState.cull = false;
  9994. }
  9995. }
  9996. // Z offset
  9997. this.setZOffset(zOffset);
  9998. };
  9999. Engine.prototype.setZOffset = function (value) {
  10000. this._depthCullingState.zOffset = value;
  10001. };
  10002. Engine.prototype.getZOffset = function () {
  10003. return this._depthCullingState.zOffset;
  10004. };
  10005. Engine.prototype.setDepthBuffer = function (enable) {
  10006. this._depthCullingState.depthTest = enable;
  10007. };
  10008. Engine.prototype.getDepthWrite = function () {
  10009. return this._depthCullingState.depthMask;
  10010. };
  10011. Engine.prototype.setDepthWrite = function (enable) {
  10012. this._depthCullingState.depthMask = enable;
  10013. };
  10014. Engine.prototype.setColorWrite = function (enable) {
  10015. this._gl.colorMask(enable, enable, enable, enable);
  10016. this._colorWrite = enable;
  10017. };
  10018. Engine.prototype.getColorWrite = function () {
  10019. return this._colorWrite;
  10020. };
  10021. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10022. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10023. };
  10024. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10025. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10026. if (this._alphaMode === mode) {
  10027. return;
  10028. }
  10029. switch (mode) {
  10030. case Engine.ALPHA_DISABLE:
  10031. this._alphaState.alphaBlend = false;
  10032. break;
  10033. case Engine.ALPHA_PREMULTIPLIED:
  10034. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10035. this._alphaState.alphaBlend = true;
  10036. break;
  10037. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10038. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10039. this._alphaState.alphaBlend = true;
  10040. break;
  10041. case Engine.ALPHA_COMBINE:
  10042. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10043. this._alphaState.alphaBlend = true;
  10044. break;
  10045. case Engine.ALPHA_ONEONE:
  10046. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10047. this._alphaState.alphaBlend = true;
  10048. break;
  10049. case Engine.ALPHA_ADD:
  10050. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10051. this._alphaState.alphaBlend = true;
  10052. break;
  10053. case Engine.ALPHA_SUBTRACT:
  10054. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10055. this._alphaState.alphaBlend = true;
  10056. break;
  10057. case Engine.ALPHA_MULTIPLY:
  10058. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10059. this._alphaState.alphaBlend = true;
  10060. break;
  10061. case Engine.ALPHA_MAXIMIZED:
  10062. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10063. this._alphaState.alphaBlend = true;
  10064. break;
  10065. case Engine.ALPHA_INTERPOLATE:
  10066. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10067. this._alphaState.alphaBlend = true;
  10068. break;
  10069. case Engine.ALPHA_SCREENMODE:
  10070. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10071. this._alphaState.alphaBlend = true;
  10072. break;
  10073. }
  10074. if (!noDepthWriteChange) {
  10075. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10076. }
  10077. this._alphaMode = mode;
  10078. };
  10079. Engine.prototype.getAlphaMode = function () {
  10080. return this._alphaMode;
  10081. };
  10082. Engine.prototype.setAlphaTesting = function (enable) {
  10083. this._alphaTest = enable;
  10084. };
  10085. Engine.prototype.getAlphaTesting = function () {
  10086. return !!this._alphaTest;
  10087. };
  10088. // Textures
  10089. Engine.prototype.wipeCaches = function (bruteForce) {
  10090. if (this.preventCacheWipeBetweenFrames) {
  10091. return;
  10092. }
  10093. this.resetTextureCache();
  10094. this._currentEffect = null;
  10095. // 6/8/2017: deltakosh: Should not be required anymore.
  10096. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  10097. if (bruteForce) {
  10098. this._currentProgram = null;
  10099. this._stencilState.reset();
  10100. this._depthCullingState.reset();
  10101. this.setDepthFunctionToLessOrEqual();
  10102. this._alphaState.reset();
  10103. }
  10104. this._cachedVertexBuffers = null;
  10105. this._cachedIndexBuffer = null;
  10106. this._cachedEffectForVertexBuffers = null;
  10107. this._unbindVertexArrayObject();
  10108. this.bindIndexBuffer(null);
  10109. this.bindArrayBuffer(null);
  10110. };
  10111. /**
  10112. * Set the compressed texture format to use, based on the formats you have, and the formats
  10113. * supported by the hardware / browser.
  10114. *
  10115. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10116. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10117. * to API arguments needed to compressed textures. This puts the burden on the container
  10118. * generator to house the arcane code for determining these for current & future formats.
  10119. *
  10120. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10121. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10122. *
  10123. * Note: The result of this call is not taken into account when a texture is base64.
  10124. *
  10125. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10126. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10127. *
  10128. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10129. * @returns The extension selected.
  10130. */
  10131. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10132. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10133. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10134. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10135. return this._textureFormatInUse = this._texturesSupported[i];
  10136. }
  10137. }
  10138. }
  10139. // actively set format to nothing, to allow this to be called more than once
  10140. // and possibly fail the 2nd time
  10141. this._textureFormatInUse = null;
  10142. return null;
  10143. };
  10144. Engine.prototype._createTexture = function () {
  10145. var texture = this._gl.createTexture();
  10146. if (!texture) {
  10147. throw new Error("Unable to create texture");
  10148. }
  10149. return texture;
  10150. };
  10151. /**
  10152. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10153. * @param {string} urlArg- This contains one of the following:
  10154. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10155. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10156. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10157. *
  10158. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10159. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10160. * @param {Scene} scene- Needed for loading to the correct scene.
  10161. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10162. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10163. * @param {callback} onError- Optional callback to be called upon failure.
  10164. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10165. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10166. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10167. *
  10168. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10169. */
  10170. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10171. var _this = this;
  10172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10173. if (onLoad === void 0) { onLoad = null; }
  10174. if (onError === void 0) { onError = null; }
  10175. if (buffer === void 0) { buffer = null; }
  10176. if (fallBack === void 0) { fallBack = null; }
  10177. if (format === void 0) { format = null; }
  10178. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10179. var fromData = url.substr(0, 5) === "data:";
  10180. var fromBlob = url.substr(0, 5) === "blob:";
  10181. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10182. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10183. // establish the file extension, if possible
  10184. var lastDot = url.lastIndexOf('.');
  10185. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10186. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10187. var isTGA = (extension === ".tga");
  10188. // determine if a ktx file should be substituted
  10189. var isKTX = false;
  10190. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10191. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10192. isKTX = true;
  10193. }
  10194. if (scene) {
  10195. scene._addPendingData(texture);
  10196. }
  10197. texture.url = url;
  10198. texture.generateMipMaps = !noMipmap;
  10199. texture.samplingMode = samplingMode;
  10200. texture.invertY = invertY;
  10201. if (!this._doNotHandleContextLost) {
  10202. // Keep a link to the buffer only if we plan to handle context lost
  10203. texture._buffer = buffer;
  10204. }
  10205. if (onLoad) {
  10206. texture.onLoadedObservable.add(onLoad);
  10207. }
  10208. if (!fallBack)
  10209. this._internalTexturesCache.push(texture);
  10210. var onerror = function () {
  10211. if (scene) {
  10212. scene._removePendingData(texture);
  10213. }
  10214. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10215. if (isKTX) {
  10216. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10217. }
  10218. else if ((isTGA || isDDS) && BABYLON.Tools.UseFallbackTexture) {
  10219. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10220. }
  10221. else if (onError) {
  10222. onError();
  10223. }
  10224. };
  10225. var callback = null;
  10226. // processing for non-image formats
  10227. if (isKTX || isTGA || isDDS) {
  10228. if (isKTX) {
  10229. callback = function (data) {
  10230. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10231. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10232. ktx.uploadLevels(_this._gl, !noMipmap);
  10233. return false;
  10234. }, samplingMode);
  10235. };
  10236. }
  10237. else if (isTGA) {
  10238. callback = function (arrayBuffer) {
  10239. var data = new Uint8Array(arrayBuffer);
  10240. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10241. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10242. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10243. return false;
  10244. }, samplingMode);
  10245. };
  10246. }
  10247. else if (isDDS) {
  10248. callback = function (data) {
  10249. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10250. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10251. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10252. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10253. return false;
  10254. }, samplingMode);
  10255. };
  10256. }
  10257. if (!buffer) {
  10258. BABYLON.Tools.LoadFile(url, function (data) {
  10259. if (callback) {
  10260. callback(data);
  10261. }
  10262. }, undefined, scene ? scene.database : undefined, true, onerror);
  10263. }
  10264. else {
  10265. if (callback) {
  10266. callback(buffer);
  10267. }
  10268. }
  10269. // image format processing
  10270. }
  10271. else {
  10272. var onload = function (img) {
  10273. if (fromBlob && !_this._doNotHandleContextLost) {
  10274. // We need to store the image if we need to rebuild the texture
  10275. // in case of a webgl context lost
  10276. texture._buffer = img;
  10277. }
  10278. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10279. var gl = _this._gl;
  10280. var isPot = (img.width === potWidth && img.height === potHeight);
  10281. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10282. if (isPot) {
  10283. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10284. return false;
  10285. }
  10286. // Using shaders to rescale because canvas.drawImage is lossy
  10287. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10288. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  10289. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10290. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10291. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10292. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10293. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10294. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10295. _this._releaseTexture(source);
  10296. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10297. continuationCallback();
  10298. });
  10299. return true;
  10300. }, samplingMode);
  10301. };
  10302. if (!fromData || isBase64)
  10303. if (buffer instanceof HTMLImageElement) {
  10304. onload(buffer);
  10305. }
  10306. else {
  10307. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10308. }
  10309. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10310. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10311. else
  10312. onload(buffer);
  10313. }
  10314. return texture;
  10315. };
  10316. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10317. var _this = this;
  10318. var rtt = this.createRenderTargetTexture({
  10319. width: destination.width,
  10320. height: destination.height,
  10321. }, {
  10322. generateMipMaps: false,
  10323. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10324. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10325. generateDepthBuffer: false,
  10326. generateStencilBuffer: false
  10327. });
  10328. if (!this._rescalePostProcess) {
  10329. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10330. }
  10331. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10332. _this._rescalePostProcess.onApply = function (effect) {
  10333. effect._bindTexture("textureSampler", source);
  10334. };
  10335. var hostingScene = scene;
  10336. if (!hostingScene) {
  10337. hostingScene = _this.scenes[_this.scenes.length - 1];
  10338. }
  10339. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  10340. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  10341. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10342. _this.unBindFramebuffer(rtt);
  10343. _this._releaseTexture(rtt);
  10344. if (onComplete) {
  10345. onComplete();
  10346. }
  10347. });
  10348. };
  10349. Engine.prototype._getInternalFormat = function (format) {
  10350. var internalFormat = this._gl.RGBA;
  10351. switch (format) {
  10352. case Engine.TEXTUREFORMAT_ALPHA:
  10353. internalFormat = this._gl.ALPHA;
  10354. break;
  10355. case Engine.TEXTUREFORMAT_LUMINANCE:
  10356. internalFormat = this._gl.LUMINANCE;
  10357. break;
  10358. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10359. internalFormat = this._gl.LUMINANCE_ALPHA;
  10360. break;
  10361. case Engine.TEXTUREFORMAT_RGB:
  10362. internalFormat = this._gl.RGB;
  10363. break;
  10364. case Engine.TEXTUREFORMAT_RGBA:
  10365. internalFormat = this._gl.RGBA;
  10366. break;
  10367. }
  10368. return internalFormat;
  10369. };
  10370. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  10371. if (compression === void 0) { compression = null; }
  10372. if (!texture) {
  10373. return;
  10374. }
  10375. var internalFormat = this._getInternalFormat(format);
  10376. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10377. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10378. if (!this._doNotHandleContextLost) {
  10379. texture._bufferView = data;
  10380. texture.format = format;
  10381. texture.invertY = invertY;
  10382. texture._compression = compression;
  10383. }
  10384. if (texture.width % 4 !== 0) {
  10385. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10386. }
  10387. if (compression && data) {
  10388. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10389. }
  10390. else {
  10391. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  10392. }
  10393. if (texture.generateMipMaps) {
  10394. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10395. }
  10396. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10397. this.resetTextureCache();
  10398. texture.isReady = true;
  10399. };
  10400. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  10401. if (compression === void 0) { compression = null; }
  10402. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10403. texture.baseWidth = width;
  10404. texture.baseHeight = height;
  10405. texture.width = width;
  10406. texture.height = height;
  10407. texture.format = format;
  10408. texture.generateMipMaps = generateMipMaps;
  10409. texture.samplingMode = samplingMode;
  10410. texture.invertY = invertY;
  10411. texture._compression = compression;
  10412. if (!this._doNotHandleContextLost) {
  10413. texture._bufferView = data;
  10414. }
  10415. this.updateRawTexture(texture, data, format, invertY, compression);
  10416. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10417. // Filters
  10418. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10419. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10420. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10421. if (generateMipMaps) {
  10422. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10423. }
  10424. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10425. this._internalTexturesCache.push(texture);
  10426. return texture;
  10427. };
  10428. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10429. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10430. texture.baseWidth = width;
  10431. texture.baseHeight = height;
  10432. if (generateMipMaps) {
  10433. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10434. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10435. }
  10436. this.resetTextureCache();
  10437. texture.width = width;
  10438. texture.height = height;
  10439. texture.isReady = false;
  10440. texture.generateMipMaps = generateMipMaps;
  10441. texture.samplingMode = samplingMode;
  10442. this.updateTextureSamplingMode(samplingMode, texture);
  10443. this._internalTexturesCache.push(texture);
  10444. return texture;
  10445. };
  10446. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10447. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10448. if (texture.isCube) {
  10449. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10450. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10451. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10452. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10453. }
  10454. else if (texture.is3D) {
  10455. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  10456. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10457. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10458. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10459. }
  10460. else {
  10461. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10462. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10463. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10464. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10465. }
  10466. texture.samplingMode = samplingMode;
  10467. };
  10468. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10469. if (premulAlpha === void 0) { premulAlpha = false; }
  10470. if (!texture) {
  10471. return;
  10472. }
  10473. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10474. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10475. if (premulAlpha) {
  10476. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10477. }
  10478. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10479. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10480. if (texture.generateMipMaps) {
  10481. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10482. }
  10483. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10484. if (premulAlpha) {
  10485. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10486. }
  10487. this.resetTextureCache();
  10488. texture.isReady = true;
  10489. };
  10490. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10491. if (!texture || texture._isDisabled) {
  10492. return;
  10493. }
  10494. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10495. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10496. try {
  10497. // Testing video texture support
  10498. if (this._videoTextureSupported === undefined) {
  10499. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10500. if (this._gl.getError() !== 0) {
  10501. this._videoTextureSupported = false;
  10502. }
  10503. else {
  10504. this._videoTextureSupported = true;
  10505. }
  10506. }
  10507. // Copy video through the current working canvas if video texture is not supported
  10508. if (!this._videoTextureSupported) {
  10509. if (!texture._workingCanvas) {
  10510. texture._workingCanvas = document.createElement("canvas");
  10511. var context = texture._workingCanvas.getContext("2d");
  10512. if (!context) {
  10513. throw new Error("Unable to get 2d context");
  10514. }
  10515. texture._workingContext = context;
  10516. texture._workingCanvas.width = texture.width;
  10517. texture._workingCanvas.height = texture.height;
  10518. }
  10519. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10520. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10521. }
  10522. else {
  10523. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10524. }
  10525. if (texture.generateMipMaps) {
  10526. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10527. }
  10528. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10529. this.resetTextureCache();
  10530. texture.isReady = true;
  10531. }
  10532. catch (ex) {
  10533. // Something unexpected
  10534. // Let's disable the texture
  10535. texture._isDisabled = true;
  10536. }
  10537. };
  10538. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10539. var fullOptions = new RenderTargetCreationOptions();
  10540. if (options !== undefined && typeof options === "object") {
  10541. fullOptions.generateMipMaps = options.generateMipMaps;
  10542. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10543. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10544. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10545. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10546. }
  10547. else {
  10548. fullOptions.generateMipMaps = options;
  10549. fullOptions.generateDepthBuffer = true;
  10550. fullOptions.generateStencilBuffer = false;
  10551. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10552. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10553. }
  10554. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10555. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10556. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10557. }
  10558. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10559. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10560. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10561. }
  10562. var gl = this._gl;
  10563. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10564. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10565. var width = size.width || size;
  10566. var height = size.height || size;
  10567. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10568. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10569. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10570. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10571. }
  10572. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10573. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10574. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10575. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10576. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10577. // Create the framebuffer
  10578. var framebuffer = gl.createFramebuffer();
  10579. this.bindUnboundFramebuffer(framebuffer);
  10580. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10581. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10582. if (fullOptions.generateMipMaps) {
  10583. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10584. }
  10585. // Unbind
  10586. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10587. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10588. this.bindUnboundFramebuffer(null);
  10589. texture._framebuffer = framebuffer;
  10590. texture.baseWidth = width;
  10591. texture.baseHeight = height;
  10592. texture.width = width;
  10593. texture.height = height;
  10594. texture.isReady = true;
  10595. texture.samples = 1;
  10596. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10597. texture.samplingMode = fullOptions.samplingMode;
  10598. texture.type = fullOptions.type;
  10599. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10600. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10601. this.resetTextureCache();
  10602. this._internalTexturesCache.push(texture);
  10603. return texture;
  10604. };
  10605. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10606. var generateMipMaps = false;
  10607. var generateDepthBuffer = true;
  10608. var generateStencilBuffer = false;
  10609. var generateDepthTexture = false;
  10610. var textureCount = 1;
  10611. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10612. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10613. var types = [], samplingModes = [];
  10614. if (options !== undefined) {
  10615. generateMipMaps = options.generateMipMaps;
  10616. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10617. generateStencilBuffer = options.generateStencilBuffer;
  10618. generateDepthTexture = options.generateDepthTexture;
  10619. textureCount = options.textureCount || 1;
  10620. if (options.types) {
  10621. types = options.types;
  10622. }
  10623. if (options.samplingModes) {
  10624. samplingModes = options.samplingModes;
  10625. }
  10626. }
  10627. var gl = this._gl;
  10628. // Create the framebuffer
  10629. var framebuffer = gl.createFramebuffer();
  10630. this.bindUnboundFramebuffer(framebuffer);
  10631. var width = size.width || size;
  10632. var height = size.height || size;
  10633. var textures = [];
  10634. var attachments = [];
  10635. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10636. for (var i = 0; i < textureCount; i++) {
  10637. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10638. var type = types[i] || defaultType;
  10639. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10640. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10641. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10642. }
  10643. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10644. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10645. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10646. }
  10647. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10648. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10649. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10650. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10651. }
  10652. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10653. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10654. textures.push(texture);
  10655. attachments.push(attachment);
  10656. gl.activeTexture(gl["TEXTURE" + i]);
  10657. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10658. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10659. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10660. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10661. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10662. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10663. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10664. if (generateMipMaps) {
  10665. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10666. }
  10667. // Unbind
  10668. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10669. texture._framebuffer = framebuffer;
  10670. texture._depthStencilBuffer = depthStencilBuffer;
  10671. texture.baseWidth = width;
  10672. texture.baseHeight = height;
  10673. texture.width = width;
  10674. texture.height = height;
  10675. texture.isReady = true;
  10676. texture.samples = 1;
  10677. texture.generateMipMaps = generateMipMaps;
  10678. texture.samplingMode = samplingMode;
  10679. texture.type = type;
  10680. texture._generateDepthBuffer = generateDepthBuffer;
  10681. texture._generateStencilBuffer = generateStencilBuffer;
  10682. this._internalTexturesCache.push(texture);
  10683. }
  10684. if (generateDepthTexture && this._caps.depthTextureExtension) {
  10685. // Depth texture
  10686. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10687. gl.activeTexture(gl.TEXTURE0);
  10688. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10689. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10690. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10691. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10693. gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10694. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10695. depthTexture._framebuffer = framebuffer;
  10696. depthTexture.baseWidth = width;
  10697. depthTexture.baseHeight = height;
  10698. depthTexture.width = width;
  10699. depthTexture.height = height;
  10700. depthTexture.isReady = true;
  10701. depthTexture.samples = 1;
  10702. depthTexture.generateMipMaps = generateMipMaps;
  10703. depthTexture.samplingMode = gl.NEAREST;
  10704. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10705. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10706. textures.push(depthTexture);
  10707. this._internalTexturesCache.push(depthTexture);
  10708. }
  10709. gl.drawBuffers(attachments);
  10710. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10711. this.bindUnboundFramebuffer(null);
  10712. this.resetTextureCache();
  10713. return textures;
  10714. };
  10715. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10716. if (samples === void 0) { samples = 1; }
  10717. var depthStencilBuffer = null;
  10718. var gl = this._gl;
  10719. // Create the depth/stencil buffer
  10720. if (generateStencilBuffer) {
  10721. depthStencilBuffer = gl.createRenderbuffer();
  10722. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10723. if (samples > 1) {
  10724. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10725. }
  10726. else {
  10727. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10728. }
  10729. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10730. }
  10731. else if (generateDepthBuffer) {
  10732. depthStencilBuffer = gl.createRenderbuffer();
  10733. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10734. if (samples > 1) {
  10735. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10736. }
  10737. else {
  10738. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10739. }
  10740. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10741. }
  10742. return depthStencilBuffer;
  10743. };
  10744. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10745. if (this.webGLVersion < 2 || !texture) {
  10746. return 1;
  10747. }
  10748. if (texture.samples === samples) {
  10749. return samples;
  10750. }
  10751. var gl = this._gl;
  10752. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10753. // Dispose previous render buffers
  10754. if (texture._depthStencilBuffer) {
  10755. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10756. }
  10757. if (texture._MSAAFramebuffer) {
  10758. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10759. }
  10760. if (texture._MSAARenderBuffer) {
  10761. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10762. }
  10763. if (samples > 1) {
  10764. var framebuffer = gl.createFramebuffer();
  10765. if (!framebuffer) {
  10766. throw new Error("Unable to create multi sampled framebuffer");
  10767. }
  10768. texture._MSAAFramebuffer = framebuffer;
  10769. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10770. var colorRenderbuffer = gl.createRenderbuffer();
  10771. if (!colorRenderbuffer) {
  10772. throw new Error("Unable to create multi sampled framebuffer");
  10773. }
  10774. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10775. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10776. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10777. texture._MSAARenderBuffer = colorRenderbuffer;
  10778. }
  10779. else {
  10780. this.bindUnboundFramebuffer(texture._framebuffer);
  10781. }
  10782. texture.samples = samples;
  10783. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10784. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10785. this.bindUnboundFramebuffer(null);
  10786. return samples;
  10787. };
  10788. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10789. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10790. };
  10791. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10792. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10793. };
  10794. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10795. var gl = this._gl;
  10796. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10797. var generateMipMaps = true;
  10798. var generateDepthBuffer = true;
  10799. var generateStencilBuffer = false;
  10800. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10801. if (options !== undefined) {
  10802. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10803. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10804. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  10805. if (options.samplingMode !== undefined) {
  10806. samplingMode = options.samplingMode;
  10807. }
  10808. }
  10809. texture.isCube = true;
  10810. texture.generateMipMaps = generateMipMaps;
  10811. texture.samples = 1;
  10812. texture.samplingMode = samplingMode;
  10813. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10814. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10815. for (var face = 0; face < 6; face++) {
  10816. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10817. }
  10818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10822. // Create the framebuffer
  10823. var framebuffer = gl.createFramebuffer();
  10824. this.bindUnboundFramebuffer(framebuffer);
  10825. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10826. // Mipmaps
  10827. if (texture.generateMipMaps) {
  10828. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10829. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10830. }
  10831. // Unbind
  10832. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10833. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10834. this.bindUnboundFramebuffer(null);
  10835. texture._framebuffer = framebuffer;
  10836. texture.width = size;
  10837. texture.height = size;
  10838. texture.isReady = true;
  10839. this.resetTextureCache();
  10840. this._internalTexturesCache.push(texture);
  10841. return texture;
  10842. };
  10843. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10844. var _this = this;
  10845. if (onLoad === void 0) { onLoad = null; }
  10846. if (onError === void 0) { onError = null; }
  10847. if (forcedExtension === void 0) { forcedExtension = null; }
  10848. var callback = function (loadData) {
  10849. if (!loadData) {
  10850. if (onLoad) {
  10851. onLoad(null);
  10852. }
  10853. return;
  10854. }
  10855. var texture = loadData.texture;
  10856. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10857. texture._lodGenerationScale = scale;
  10858. texture._lodGenerationOffset = offset;
  10859. if (_this._caps.textureLOD) {
  10860. // Do not add extra process if texture lod is supported.
  10861. if (onLoad) {
  10862. onLoad(texture);
  10863. }
  10864. return;
  10865. }
  10866. var mipSlices = 3;
  10867. var gl = _this._gl;
  10868. var width = loadData.width;
  10869. if (!width) {
  10870. return;
  10871. }
  10872. var textures = [];
  10873. for (var i = 0; i < mipSlices; i++) {
  10874. //compute LOD from even spacing in smoothness (matching shader calculation)
  10875. var smoothness = i / (mipSlices - 1);
  10876. var roughness = 1 - smoothness;
  10877. var minLODIndex = offset; // roughness = 0
  10878. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10879. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10880. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10881. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10882. glTextureFromLod.isCube = true;
  10883. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10884. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10887. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10888. if (loadData.isDDS) {
  10889. var info = loadData.info;
  10890. var data = loadData.data;
  10891. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10892. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10893. }
  10894. else {
  10895. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10896. }
  10897. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10898. // Wrap in a base texture for easy binding.
  10899. var lodTexture = new BABYLON.BaseTexture(scene);
  10900. lodTexture.isCube = true;
  10901. lodTexture._texture = glTextureFromLod;
  10902. glTextureFromLod.isReady = true;
  10903. textures.push(lodTexture);
  10904. }
  10905. texture._lodTextureHigh = textures[2];
  10906. texture._lodTextureMid = textures[1];
  10907. texture._lodTextureLow = textures[0];
  10908. if (onLoad) {
  10909. onLoad(texture);
  10910. }
  10911. };
  10912. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10913. };
  10914. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10915. var _this = this;
  10916. if (onLoad === void 0) { onLoad = null; }
  10917. if (onError === void 0) { onError = null; }
  10918. if (forcedExtension === void 0) { forcedExtension = null; }
  10919. var gl = this._gl;
  10920. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10921. texture.isCube = true;
  10922. texture.url = rootUrl;
  10923. texture.generateMipMaps = !noMipmap;
  10924. if (!this._doNotHandleContextLost) {
  10925. texture._extension = forcedExtension;
  10926. texture._files = files;
  10927. }
  10928. var isKTX = false;
  10929. var isDDS = false;
  10930. var lastDot = rootUrl.lastIndexOf('.');
  10931. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  10932. if (this._textureFormatInUse) {
  10933. extension = this._textureFormatInUse;
  10934. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  10935. isKTX = true;
  10936. }
  10937. else {
  10938. isDDS = (extension === ".dds");
  10939. }
  10940. var onerror = function (request, exception) {
  10941. if (onError) {
  10942. onError(request.status + " " + request.statusText, exception);
  10943. }
  10944. };
  10945. if (isKTX) {
  10946. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10947. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10948. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10949. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10950. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10951. ktx.uploadLevels(_this._gl, !noMipmap);
  10952. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10953. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10954. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10955. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10956. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10957. _this.resetTextureCache();
  10958. texture.width = ktx.pixelWidth;
  10959. texture.height = ktx.pixelHeight;
  10960. texture.isReady = true;
  10961. }, undefined, undefined, true, onerror);
  10962. }
  10963. else if (isDDS) {
  10964. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10965. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10966. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10967. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10968. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10969. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10970. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10971. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10972. }
  10973. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10974. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10975. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10976. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10977. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10978. _this.resetTextureCache();
  10979. texture.width = info.width;
  10980. texture.height = info.height;
  10981. texture.isReady = true;
  10982. texture.type = info.textureType;
  10983. if (onLoad) {
  10984. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10985. }
  10986. }, undefined, undefined, true, onerror);
  10987. }
  10988. else {
  10989. if (!files) {
  10990. throw new Error("Cannot load cubemap because files were not defined");
  10991. }
  10992. cascadeLoad(rootUrl, scene, function (imgs) {
  10993. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10994. var height = width;
  10995. _this._prepareWorkingCanvas();
  10996. if (!_this._workingCanvas || !_this._workingContext) {
  10997. return;
  10998. }
  10999. _this._workingCanvas.width = width;
  11000. _this._workingCanvas.height = height;
  11001. var faces = [
  11002. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11003. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11004. ];
  11005. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11006. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11007. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11008. for (var index = 0; index < faces.length; index++) {
  11009. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11010. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11011. }
  11012. if (!noMipmap) {
  11013. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11014. }
  11015. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11016. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  11017. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11018. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11019. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11020. _this.resetTextureCache();
  11021. texture.width = width;
  11022. texture.height = height;
  11023. texture.isReady = true;
  11024. if (format) {
  11025. texture.format = format;
  11026. }
  11027. texture.onLoadedObservable.notifyObservers(texture);
  11028. texture.onLoadedObservable.clear();
  11029. if (onLoad) {
  11030. onLoad();
  11031. }
  11032. }, files, onError);
  11033. }
  11034. this._internalTexturesCache.push(texture);
  11035. return texture;
  11036. };
  11037. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11038. if (compression === void 0) { compression = null; }
  11039. if (level === void 0) { level = 0; }
  11040. texture._bufferViewArray = data;
  11041. texture.format = format;
  11042. texture.type = type;
  11043. texture.invertY = invertY;
  11044. texture._compression = compression;
  11045. var gl = this._gl;
  11046. var textureType = this._getWebGLTextureType(type);
  11047. var internalFormat = this._getInternalFormat(format);
  11048. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11049. var needConversion = false;
  11050. if (internalFormat === gl.RGB) {
  11051. internalFormat = gl.RGBA;
  11052. needConversion = true;
  11053. }
  11054. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11055. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11056. if (texture.width % 4 !== 0) {
  11057. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11058. }
  11059. // Data are known to be in +X +Y +Z -X -Y -Z
  11060. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11061. var faceData = data[faceIndex];
  11062. if (compression) {
  11063. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11064. }
  11065. else {
  11066. if (needConversion) {
  11067. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11068. }
  11069. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11070. }
  11071. }
  11072. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11073. if (isPot && texture.generateMipMaps && level === 0) {
  11074. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11075. }
  11076. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11077. this.resetTextureCache();
  11078. texture.isReady = true;
  11079. };
  11080. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11081. if (compression === void 0) { compression = null; }
  11082. var gl = this._gl;
  11083. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11084. texture.isCube = true;
  11085. texture.generateMipMaps = generateMipMaps;
  11086. texture.format = format;
  11087. texture.type = type;
  11088. if (!this._doNotHandleContextLost) {
  11089. texture._bufferViewArray = data;
  11090. }
  11091. var textureType = this._getWebGLTextureType(type);
  11092. var internalFormat = this._getInternalFormat(format);
  11093. var needConversion = false;
  11094. if (internalFormat === gl.RGB) {
  11095. internalFormat = gl.RGBA;
  11096. needConversion = true;
  11097. }
  11098. var width = size;
  11099. var height = width;
  11100. texture.width = width;
  11101. texture.height = height;
  11102. // Double check on POT to generate Mips.
  11103. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11104. if (!isPot) {
  11105. generateMipMaps = false;
  11106. }
  11107. // Upload data if needed. The texture won't be ready until then.
  11108. if (data) {
  11109. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11110. }
  11111. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  11112. // Filters
  11113. if (data && generateMipMaps) {
  11114. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11115. }
  11116. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11117. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11118. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11119. }
  11120. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11121. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11122. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11123. }
  11124. else {
  11125. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11126. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11127. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11128. }
  11129. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11130. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11131. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11132. return texture;
  11133. };
  11134. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11135. var _this = this;
  11136. if (onLoad === void 0) { onLoad = null; }
  11137. if (onError === void 0) { onError = null; }
  11138. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11139. if (invertY === void 0) { invertY = false; }
  11140. var gl = this._gl;
  11141. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11142. scene._addPendingData(texture);
  11143. texture.url = url;
  11144. this._internalTexturesCache.push(texture);
  11145. var onerror = function (request, exception) {
  11146. scene._removePendingData(texture);
  11147. if (onError) {
  11148. onError(request.status + " " + request.statusText, exception);
  11149. }
  11150. };
  11151. var internalCallback = function (data) {
  11152. var width = texture.width;
  11153. var faceDataArrays = callback(data);
  11154. if (!faceDataArrays) {
  11155. return;
  11156. }
  11157. if (mipmmapGenerator) {
  11158. var textureType = _this._getWebGLTextureType(type);
  11159. var internalFormat = _this._getInternalFormat(format);
  11160. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11161. var needConversion = false;
  11162. if (internalFormat === gl.RGB) {
  11163. internalFormat = gl.RGBA;
  11164. needConversion = true;
  11165. }
  11166. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  11167. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11168. var mipData = mipmmapGenerator(faceDataArrays);
  11169. for (var level = 0; level < mipData.length; level++) {
  11170. var mipSize = width >> level;
  11171. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11172. var mipFaceData = mipData[level][faceIndex];
  11173. if (needConversion) {
  11174. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11175. }
  11176. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11177. }
  11178. }
  11179. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11180. }
  11181. else {
  11182. texture.generateMipMaps = !noMipmap;
  11183. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11184. }
  11185. texture.isReady = true;
  11186. _this.resetTextureCache();
  11187. scene._removePendingData(texture);
  11188. if (onLoad) {
  11189. onLoad();
  11190. }
  11191. };
  11192. BABYLON.Tools.LoadFile(url, function (data) {
  11193. internalCallback(data);
  11194. }, undefined, scene.database, true, onerror);
  11195. return texture;
  11196. };
  11197. ;
  11198. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11199. if (compression === void 0) { compression = null; }
  11200. var internalFormat = this._getInternalFormat(format);
  11201. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11202. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11203. if (!this._doNotHandleContextLost) {
  11204. texture._bufferView = data;
  11205. texture.format = format;
  11206. texture.invertY = invertY;
  11207. texture._compression = compression;
  11208. }
  11209. if (texture.width % 4 !== 0) {
  11210. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11211. }
  11212. if (compression && data) {
  11213. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11214. }
  11215. else {
  11216. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11217. }
  11218. if (texture.generateMipMaps) {
  11219. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11220. }
  11221. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11222. this.resetTextureCache();
  11223. texture.isReady = true;
  11224. };
  11225. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11226. if (compression === void 0) { compression = null; }
  11227. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11228. texture.baseWidth = width;
  11229. texture.baseHeight = height;
  11230. texture.baseDepth = depth;
  11231. texture.width = width;
  11232. texture.height = height;
  11233. texture.depth = depth;
  11234. texture.format = format;
  11235. texture.generateMipMaps = generateMipMaps;
  11236. texture.samplingMode = samplingMode;
  11237. texture.is3D = true;
  11238. if (!this._doNotHandleContextLost) {
  11239. texture._bufferView = data;
  11240. }
  11241. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11242. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture);
  11243. // Filters
  11244. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11245. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11246. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11247. if (generateMipMaps) {
  11248. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11249. }
  11250. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11251. this._internalTexturesCache.push(texture);
  11252. return texture;
  11253. };
  11254. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11255. var gl = this._gl;
  11256. if (!gl) {
  11257. return;
  11258. }
  11259. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11260. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11261. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11262. if (!noMipmap && !isCompressed) {
  11263. gl.generateMipmap(gl.TEXTURE_2D);
  11264. }
  11265. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11266. this.resetTextureCache();
  11267. if (scene) {
  11268. scene._removePendingData(texture);
  11269. }
  11270. texture.onLoadedObservable.notifyObservers(texture);
  11271. texture.onLoadedObservable.clear();
  11272. };
  11273. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11274. var _this = this;
  11275. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11276. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11277. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11278. var gl = this._gl;
  11279. if (!gl) {
  11280. return;
  11281. }
  11282. if (!texture._webGLTexture) {
  11283. this.resetTextureCache();
  11284. if (scene) {
  11285. scene._removePendingData(texture);
  11286. }
  11287. return;
  11288. }
  11289. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11290. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11291. texture.baseWidth = width;
  11292. texture.baseHeight = height;
  11293. texture.width = potWidth;
  11294. texture.height = potHeight;
  11295. texture.isReady = true;
  11296. if (processFunction(potWidth, potHeight, function () {
  11297. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11298. })) {
  11299. // Returning as texture needs extra async steps
  11300. return;
  11301. }
  11302. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11303. };
  11304. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11305. // Create new RGBA data container.
  11306. var rgbaData;
  11307. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11308. rgbaData = new Float32Array(width * height * 4);
  11309. }
  11310. else {
  11311. rgbaData = new Uint32Array(width * height * 4);
  11312. }
  11313. // Convert each pixel.
  11314. for (var x = 0; x < width; x++) {
  11315. for (var y = 0; y < height; y++) {
  11316. var index = (y * width + x) * 3;
  11317. var newIndex = (y * width + x) * 4;
  11318. // Map Old Value to new value.
  11319. rgbaData[newIndex + 0] = rgbData[index + 0];
  11320. rgbaData[newIndex + 1] = rgbData[index + 1];
  11321. rgbaData[newIndex + 2] = rgbData[index + 2];
  11322. // Add fully opaque alpha channel.
  11323. rgbaData[newIndex + 3] = 1;
  11324. }
  11325. }
  11326. return rgbaData;
  11327. };
  11328. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11329. var gl = this._gl;
  11330. if (texture._framebuffer) {
  11331. gl.deleteFramebuffer(texture._framebuffer);
  11332. texture._framebuffer = null;
  11333. }
  11334. if (texture._depthStencilBuffer) {
  11335. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11336. texture._depthStencilBuffer = null;
  11337. }
  11338. if (texture._MSAAFramebuffer) {
  11339. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11340. texture._MSAAFramebuffer = null;
  11341. }
  11342. if (texture._MSAARenderBuffer) {
  11343. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11344. texture._MSAARenderBuffer = null;
  11345. }
  11346. };
  11347. Engine.prototype._releaseTexture = function (texture) {
  11348. var gl = this._gl;
  11349. this._releaseFramebufferObjects(texture);
  11350. gl.deleteTexture(texture._webGLTexture);
  11351. // Unbind channels
  11352. this.unbindAllTextures();
  11353. var index = this._internalTexturesCache.indexOf(texture);
  11354. if (index !== -1) {
  11355. this._internalTexturesCache.splice(index, 1);
  11356. }
  11357. // Integrated fixed lod samplers.
  11358. if (texture._lodTextureHigh) {
  11359. texture._lodTextureHigh.dispose();
  11360. }
  11361. if (texture._lodTextureMid) {
  11362. texture._lodTextureMid.dispose();
  11363. }
  11364. if (texture._lodTextureLow) {
  11365. texture._lodTextureLow.dispose();
  11366. }
  11367. };
  11368. Engine.prototype.setProgram = function (program) {
  11369. if (this._currentProgram !== program) {
  11370. this._gl.useProgram(program);
  11371. this._currentProgram = program;
  11372. }
  11373. };
  11374. Engine.prototype.bindSamplers = function (effect) {
  11375. this.setProgram(effect.getProgram());
  11376. var samplers = effect.getSamplers();
  11377. for (var index = 0; index < samplers.length; index++) {
  11378. var uniform = effect.getUniform(samplers[index]);
  11379. this._gl.uniform1i(uniform, index);
  11380. }
  11381. this._currentEffect = null;
  11382. };
  11383. Engine.prototype.activateTextureChannel = function (textureChannel) {
  11384. if (this._activeTextureChannel !== textureChannel) {
  11385. this._gl.activeTexture(textureChannel);
  11386. this._activeTextureChannel = textureChannel;
  11387. }
  11388. };
  11389. Engine.prototype._bindTextureDirectly = function (target, texture) {
  11390. if (this._activeTexturesCache[this._activeTextureChannel] !== texture) {
  11391. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11392. this._activeTexturesCache[this._activeTextureChannel] = texture;
  11393. }
  11394. };
  11395. Engine.prototype._bindTexture = function (channel, texture) {
  11396. if (channel < 0) {
  11397. return;
  11398. }
  11399. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11400. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11401. };
  11402. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11403. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11404. };
  11405. Engine.prototype.unbindAllTextures = function () {
  11406. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  11407. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11408. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11409. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11410. if (this.webGLVersion > 1) {
  11411. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11412. }
  11413. }
  11414. };
  11415. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11416. if (channel < 0) {
  11417. return;
  11418. }
  11419. if (this._setTexture(channel, texture)) {
  11420. this._gl.uniform1i(uniform, channel);
  11421. }
  11422. };
  11423. Engine.prototype._setTexture = function (channel, texture) {
  11424. // Not ready?
  11425. if (!texture) {
  11426. if (this._activeTexturesCache[channel] != null) {
  11427. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11428. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11429. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11430. if (this.webGLVersion > 1) {
  11431. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11432. }
  11433. }
  11434. return false;
  11435. }
  11436. // Video
  11437. var alreadyActivated = false;
  11438. if (texture.video) {
  11439. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11440. alreadyActivated = true;
  11441. texture.update();
  11442. }
  11443. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11444. texture.delayLoad();
  11445. return false;
  11446. }
  11447. var internalTexture;
  11448. if (texture.isReady()) {
  11449. internalTexture = texture.getInternalTexture();
  11450. }
  11451. else if (texture.isCube) {
  11452. internalTexture = this.emptyCubeTexture;
  11453. }
  11454. else if (texture.is3D) {
  11455. internalTexture = this.emptyTexture3D;
  11456. }
  11457. else {
  11458. internalTexture = this.emptyTexture;
  11459. }
  11460. if (!alreadyActivated) {
  11461. this.activateTextureChannel(this._gl.TEXTURE0 + channel);
  11462. }
  11463. if (this._activeTexturesCache[this._activeTextureChannel] === internalTexture) {
  11464. return false;
  11465. }
  11466. if (internalTexture && internalTexture.is3D) {
  11467. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture);
  11468. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11469. internalTexture._cachedWrapU = texture.wrapU;
  11470. switch (texture.wrapU) {
  11471. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11472. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11473. break;
  11474. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11475. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11476. break;
  11477. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11478. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11479. break;
  11480. }
  11481. }
  11482. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11483. internalTexture._cachedWrapV = texture.wrapV;
  11484. switch (texture.wrapV) {
  11485. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11486. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11487. break;
  11488. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11489. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11490. break;
  11491. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11492. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11493. break;
  11494. }
  11495. }
  11496. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11497. internalTexture._cachedWrapR = texture.wrapR;
  11498. switch (texture.wrapV) {
  11499. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11500. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11501. break;
  11502. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11503. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11504. break;
  11505. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11506. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11507. break;
  11508. }
  11509. }
  11510. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11511. }
  11512. else if (internalTexture && internalTexture.isCube) {
  11513. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  11514. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11515. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11516. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11517. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  11518. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  11519. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  11520. }
  11521. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  11522. }
  11523. else {
  11524. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  11525. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11526. internalTexture._cachedWrapU = texture.wrapU;
  11527. switch (texture.wrapU) {
  11528. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11529. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11530. break;
  11531. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11532. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11533. break;
  11534. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11535. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11536. break;
  11537. }
  11538. }
  11539. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11540. internalTexture._cachedWrapV = texture.wrapV;
  11541. switch (texture.wrapV) {
  11542. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11543. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11544. break;
  11545. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11546. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11547. break;
  11548. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11549. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11550. break;
  11551. }
  11552. }
  11553. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  11554. }
  11555. return true;
  11556. };
  11557. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  11558. if (channel < 0 || !uniform) {
  11559. return;
  11560. }
  11561. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  11562. this._textureUnits = new Int32Array(textures.length);
  11563. }
  11564. for (var i = 0; i < textures.length; i++) {
  11565. this._textureUnits[i] = channel + i;
  11566. }
  11567. this._gl.uniform1iv(uniform, this._textureUnits);
  11568. for (var index = 0; index < textures.length; index++) {
  11569. this._setTexture(channel + index, textures[index]);
  11570. }
  11571. };
  11572. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  11573. var internalTexture = texture.getInternalTexture();
  11574. if (!internalTexture) {
  11575. return;
  11576. }
  11577. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  11578. var value = texture.anisotropicFilteringLevel;
  11579. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  11580. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  11581. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  11582. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  11583. }
  11584. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  11585. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  11586. internalTexture._cachedAnisotropicFilteringLevel = value;
  11587. }
  11588. };
  11589. Engine.prototype.readPixels = function (x, y, width, height) {
  11590. var data = new Uint8Array(height * width * 4);
  11591. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  11592. return data;
  11593. };
  11594. /**
  11595. * Add an externaly attached data from its key.
  11596. * This method call will fail and return false, if such key already exists.
  11597. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  11598. * @param key the unique key that identifies the data
  11599. * @param data the data object to associate to the key for this Engine instance
  11600. * @return true if no such key were already present and the data was added successfully, false otherwise
  11601. */
  11602. Engine.prototype.addExternalData = function (key, data) {
  11603. if (!this._externalData) {
  11604. this._externalData = new BABYLON.StringDictionary();
  11605. }
  11606. return this._externalData.add(key, data);
  11607. };
  11608. /**
  11609. * Get an externaly attached data from its key
  11610. * @param key the unique key that identifies the data
  11611. * @return the associated data, if present (can be null), or undefined if not present
  11612. */
  11613. Engine.prototype.getExternalData = function (key) {
  11614. if (!this._externalData) {
  11615. this._externalData = new BABYLON.StringDictionary();
  11616. }
  11617. return this._externalData.get(key);
  11618. };
  11619. /**
  11620. * Get an externaly attached data from its key, create it using a factory if it's not already present
  11621. * @param key the unique key that identifies the data
  11622. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  11623. * @return the associated data, can be null if the factory returned null.
  11624. */
  11625. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  11626. if (!this._externalData) {
  11627. this._externalData = new BABYLON.StringDictionary();
  11628. }
  11629. return this._externalData.getOrAddWithFactory(key, factory);
  11630. };
  11631. /**
  11632. * Remove an externaly attached data from the Engine instance
  11633. * @param key the unique key that identifies the data
  11634. * @return true if the data was successfully removed, false if it doesn't exist
  11635. */
  11636. Engine.prototype.removeExternalData = function (key) {
  11637. if (!this._externalData) {
  11638. this._externalData = new BABYLON.StringDictionary();
  11639. }
  11640. return this._externalData.remove(key);
  11641. };
  11642. Engine.prototype.unbindAllAttributes = function () {
  11643. if (this._mustWipeVertexAttributes) {
  11644. this._mustWipeVertexAttributes = false;
  11645. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11646. this._gl.disableVertexAttribArray(i);
  11647. this._vertexAttribArraysEnabled[i] = false;
  11648. this._currentBufferPointers[i].active = false;
  11649. }
  11650. return;
  11651. }
  11652. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  11653. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  11654. continue;
  11655. }
  11656. this._gl.disableVertexAttribArray(i);
  11657. this._vertexAttribArraysEnabled[i] = false;
  11658. this._currentBufferPointers[i].active = false;
  11659. }
  11660. };
  11661. Engine.prototype.releaseEffects = function () {
  11662. for (var name in this._compiledEffects) {
  11663. this._deleteProgram(this._compiledEffects[name]._program);
  11664. }
  11665. this._compiledEffects = {};
  11666. };
  11667. // Dispose
  11668. Engine.prototype.dispose = function () {
  11669. this.hideLoadingUI();
  11670. this.stopRenderLoop();
  11671. // Release postProcesses
  11672. while (this.postProcesses.length) {
  11673. this.postProcesses[0].dispose();
  11674. }
  11675. // Empty texture
  11676. if (this._emptyTexture) {
  11677. this._releaseTexture(this._emptyTexture);
  11678. this._emptyTexture = null;
  11679. }
  11680. if (this._emptyCubeTexture) {
  11681. this._releaseTexture(this._emptyCubeTexture);
  11682. this._emptyCubeTexture = null;
  11683. }
  11684. // Rescale PP
  11685. if (this._rescalePostProcess) {
  11686. this._rescalePostProcess.dispose();
  11687. }
  11688. // Release scenes
  11689. while (this.scenes.length) {
  11690. this.scenes[0].dispose();
  11691. }
  11692. // Release audio engine
  11693. if (Engine.audioEngine) {
  11694. Engine.audioEngine.dispose();
  11695. }
  11696. // Release effects
  11697. this.releaseEffects();
  11698. // Unbind
  11699. this.unbindAllAttributes();
  11700. if (this._dummyFramebuffer) {
  11701. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  11702. }
  11703. //WebVR
  11704. this.disableVR();
  11705. // Events
  11706. window.removeEventListener("blur", this._onBlur);
  11707. window.removeEventListener("focus", this._onFocus);
  11708. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  11709. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  11710. if (this._renderingCanvas) {
  11711. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  11712. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  11713. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  11714. if (!this._doNotHandleContextLost) {
  11715. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  11716. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  11717. }
  11718. }
  11719. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  11720. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  11721. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  11722. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  11723. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  11724. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  11725. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  11726. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  11727. if (this._onVrDisplayConnect) {
  11728. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11729. if (this._onVrDisplayDisconnect) {
  11730. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11731. }
  11732. if (this._onVrDisplayPresentChange) {
  11733. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11734. }
  11735. this._onVrDisplayConnect = null;
  11736. this._onVrDisplayDisconnect = null;
  11737. }
  11738. // Remove from Instances
  11739. var index = Engine.Instances.indexOf(this);
  11740. if (index >= 0) {
  11741. Engine.Instances.splice(index, 1);
  11742. }
  11743. this._workingCanvas = null;
  11744. this._workingContext = null;
  11745. this._currentBufferPointers = [];
  11746. this._renderingCanvas = null;
  11747. this._currentProgram = null;
  11748. this.onResizeObservable.clear();
  11749. this.onCanvasBlurObservable.clear();
  11750. this.onCanvasFocusObservable.clear();
  11751. this.onCanvasPointerOutObservable.clear();
  11752. this.onBeginFrameObservable.clear();
  11753. this.onEndFrameObservable.clear();
  11754. BABYLON.Effect.ResetCache();
  11755. };
  11756. // Loading screen
  11757. Engine.prototype.displayLoadingUI = function () {
  11758. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11759. return;
  11760. }
  11761. var loadingScreen = this.loadingScreen;
  11762. if (loadingScreen) {
  11763. loadingScreen.displayLoadingUI();
  11764. }
  11765. };
  11766. Engine.prototype.hideLoadingUI = function () {
  11767. if (!BABYLON.Tools.IsWindowObjectExist()) {
  11768. return;
  11769. }
  11770. var loadingScreen = this.loadingScreen;
  11771. if (loadingScreen) {
  11772. loadingScreen.hideLoadingUI();
  11773. }
  11774. };
  11775. Object.defineProperty(Engine.prototype, "loadingScreen", {
  11776. get: function () {
  11777. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  11778. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  11779. return this._loadingScreen;
  11780. },
  11781. set: function (loadingScreen) {
  11782. this._loadingScreen = loadingScreen;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine.prototype, "loadingUIText", {
  11788. set: function (text) {
  11789. this.loadingScreen.loadingUIText = text;
  11790. },
  11791. enumerable: true,
  11792. configurable: true
  11793. });
  11794. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  11795. set: function (color) {
  11796. this.loadingScreen.loadingUIBackgroundColor = color;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Engine.prototype.attachContextLostEvent = function (callback) {
  11802. if (this._renderingCanvas) {
  11803. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  11804. }
  11805. };
  11806. Engine.prototype.attachContextRestoredEvent = function (callback) {
  11807. if (this._renderingCanvas) {
  11808. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  11809. }
  11810. };
  11811. Engine.prototype.getVertexShaderSource = function (program) {
  11812. var shaders = this._gl.getAttachedShaders(program);
  11813. if (!shaders) {
  11814. return null;
  11815. }
  11816. return this._gl.getShaderSource(shaders[0]);
  11817. };
  11818. Engine.prototype.getFragmentShaderSource = function (program) {
  11819. var shaders = this._gl.getAttachedShaders(program);
  11820. if (!shaders) {
  11821. return null;
  11822. }
  11823. return this._gl.getShaderSource(shaders[1]);
  11824. };
  11825. Engine.prototype.getError = function () {
  11826. return this._gl.getError();
  11827. };
  11828. // FPS
  11829. Engine.prototype.getFps = function () {
  11830. return this._fps;
  11831. };
  11832. Engine.prototype.getDeltaTime = function () {
  11833. return this._deltaTime;
  11834. };
  11835. Engine.prototype._measureFps = function () {
  11836. this._performanceMonitor.sampleFrame();
  11837. this._fps = this._performanceMonitor.averageFPS;
  11838. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  11839. };
  11840. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  11841. if (faceIndex === void 0) { faceIndex = -1; }
  11842. var gl = this._gl;
  11843. if (!this._dummyFramebuffer) {
  11844. var dummy = gl.createFramebuffer();
  11845. if (!dummy) {
  11846. throw new Error("Unable to create dummy framebuffer");
  11847. }
  11848. this._dummyFramebuffer = dummy;
  11849. }
  11850. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  11851. if (faceIndex > -1) {
  11852. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11853. }
  11854. else {
  11855. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11856. }
  11857. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  11858. var buffer;
  11859. switch (readType) {
  11860. case gl.UNSIGNED_BYTE:
  11861. buffer = new Uint8Array(4 * width * height);
  11862. readType = gl.UNSIGNED_BYTE;
  11863. break;
  11864. default:
  11865. buffer = new Float32Array(4 * width * height);
  11866. readType = gl.FLOAT;
  11867. break;
  11868. }
  11869. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  11870. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  11871. return buffer;
  11872. };
  11873. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11874. if (this._webGLVersion > 1) {
  11875. return this._caps.colorBufferFloat;
  11876. }
  11877. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11878. };
  11879. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11880. if (this._webGLVersion > 1) {
  11881. return this._caps.colorBufferFloat;
  11882. }
  11883. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11884. };
  11885. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11886. Engine.prototype._canRenderToFramebuffer = function (type) {
  11887. var gl = this._gl;
  11888. //clear existing errors
  11889. while (gl.getError() !== gl.NO_ERROR) { }
  11890. var successful = true;
  11891. var texture = gl.createTexture();
  11892. gl.bindTexture(gl.TEXTURE_2D, texture);
  11893. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11896. var fb = gl.createFramebuffer();
  11897. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11898. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11899. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11900. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11901. successful = successful && (gl.getError() === gl.NO_ERROR);
  11902. //try render by clearing frame buffer's color buffer
  11903. if (successful) {
  11904. gl.clear(gl.COLOR_BUFFER_BIT);
  11905. successful = successful && (gl.getError() === gl.NO_ERROR);
  11906. }
  11907. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11908. if (successful) {
  11909. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11910. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11911. var readFormat = gl.RGBA;
  11912. var readType = gl.UNSIGNED_BYTE;
  11913. var buffer = new Uint8Array(4);
  11914. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11915. successful = successful && (gl.getError() === gl.NO_ERROR);
  11916. }
  11917. //clean up
  11918. gl.deleteTexture(texture);
  11919. gl.deleteFramebuffer(fb);
  11920. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11921. //clear accumulated errors
  11922. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11923. return successful;
  11924. };
  11925. Engine.prototype._getWebGLTextureType = function (type) {
  11926. if (type === Engine.TEXTURETYPE_FLOAT) {
  11927. return this._gl.FLOAT;
  11928. }
  11929. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11930. // Add Half Float Constant.
  11931. return this._gl.HALF_FLOAT_OES;
  11932. }
  11933. return this._gl.UNSIGNED_BYTE;
  11934. };
  11935. ;
  11936. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11937. if (this._webGLVersion === 1) {
  11938. return this._gl.RGBA;
  11939. }
  11940. if (type === Engine.TEXTURETYPE_FLOAT) {
  11941. return this._gl.RGBA32F;
  11942. }
  11943. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11944. return this._gl.RGBA16F;
  11945. }
  11946. return this._gl.RGBA;
  11947. };
  11948. ;
  11949. Engine.prototype.createQuery = function () {
  11950. return this._gl.createQuery();
  11951. };
  11952. Engine.prototype.deleteQuery = function (query) {
  11953. this._gl.deleteQuery(query);
  11954. return this;
  11955. };
  11956. Engine.prototype.isQueryResultAvailable = function (query) {
  11957. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11958. };
  11959. Engine.prototype.getQueryResult = function (query) {
  11960. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11961. };
  11962. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  11963. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11964. this._gl.beginQuery(glAlgorithm, query);
  11965. return this;
  11966. };
  11967. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  11968. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11969. this._gl.endQuery(glAlgorithm);
  11970. return this;
  11971. };
  11972. /* Time queries */
  11973. Engine.prototype._createTimeQuery = function () {
  11974. var timerQuery = this._caps.timerQuery;
  11975. if (timerQuery.createQueryEXT) {
  11976. return timerQuery.createQueryEXT();
  11977. }
  11978. return this.createQuery();
  11979. };
  11980. Engine.prototype._deleteTimeQuery = function (query) {
  11981. var timerQuery = this._caps.timerQuery;
  11982. if (timerQuery.deleteQueryEXT) {
  11983. timerQuery.deleteQueryEXT(query);
  11984. return;
  11985. }
  11986. this.deleteQuery(query);
  11987. };
  11988. Engine.prototype._getTimeQueryResult = function (query) {
  11989. var timerQuery = this._caps.timerQuery;
  11990. if (timerQuery.getQueryObjectEXT) {
  11991. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  11992. }
  11993. return this.getQueryResult(query);
  11994. };
  11995. Engine.prototype._getTimeQueryAvailability = function (query) {
  11996. var timerQuery = this._caps.timerQuery;
  11997. if (timerQuery.getQueryObjectEXT) {
  11998. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  11999. }
  12000. return this.isQueryResultAvailable(query);
  12001. };
  12002. Engine.prototype.startTimeQuery = function () {
  12003. var timerQuery = this._caps.timerQuery;
  12004. if (!timerQuery) {
  12005. return null;
  12006. }
  12007. var token = new BABYLON._TimeToken();
  12008. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12009. if (this._caps.canUseTimestampForTimerQuery) {
  12010. token._startTimeQuery = this._createTimeQuery();
  12011. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12012. }
  12013. else {
  12014. if (this._currentNonTimestampToken) {
  12015. return this._currentNonTimestampToken;
  12016. }
  12017. token._timeElapsedQuery = this._createTimeQuery();
  12018. if (timerQuery.beginQueryEXT) {
  12019. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12020. }
  12021. else {
  12022. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12023. }
  12024. this._currentNonTimestampToken = token;
  12025. }
  12026. return token;
  12027. };
  12028. Engine.prototype.endTimeQuery = function (token) {
  12029. var timerQuery = this._caps.timerQuery;
  12030. if (!timerQuery || !token) {
  12031. return -1;
  12032. }
  12033. if (this._caps.canUseTimestampForTimerQuery) {
  12034. if (!token._startTimeQuery) {
  12035. return -1;
  12036. }
  12037. if (!token._endTimeQuery) {
  12038. token._endTimeQuery = this._createTimeQuery();
  12039. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12040. }
  12041. }
  12042. else if (!token._timeElapsedQueryEnded) {
  12043. if (!token._timeElapsedQuery) {
  12044. return -1;
  12045. }
  12046. if (timerQuery.endQueryEXT) {
  12047. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12048. }
  12049. else {
  12050. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12051. }
  12052. token._timeElapsedQueryEnded = true;
  12053. }
  12054. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12055. var available = false;
  12056. if (token._endTimeQuery) {
  12057. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12058. }
  12059. else if (token._timeElapsedQuery) {
  12060. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12061. }
  12062. if (available && !disjoint) {
  12063. var result = 0;
  12064. if (this._caps.canUseTimestampForTimerQuery) {
  12065. if (!token._startTimeQuery || !token._endTimeQuery) {
  12066. return -1;
  12067. }
  12068. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12069. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12070. result = timeEnd - timeStart;
  12071. this._deleteTimeQuery(token._startTimeQuery);
  12072. this._deleteTimeQuery(token._endTimeQuery);
  12073. token._startTimeQuery = null;
  12074. token._endTimeQuery = null;
  12075. }
  12076. else {
  12077. if (!token._timeElapsedQuery) {
  12078. return -1;
  12079. }
  12080. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12081. this._deleteTimeQuery(token._timeElapsedQuery);
  12082. token._timeElapsedQuery = null;
  12083. token._timeElapsedQueryEnded = false;
  12084. this._currentNonTimestampToken = null;
  12085. }
  12086. return result;
  12087. }
  12088. return -1;
  12089. };
  12090. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12091. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12092. };
  12093. // Transform feedback
  12094. Engine.prototype.createTransformFeedback = function () {
  12095. return this._gl.createTransformFeedback();
  12096. };
  12097. Engine.prototype.deleteTransformFeedback = function (value) {
  12098. this._gl.deleteTransformFeedback(value);
  12099. };
  12100. Engine.prototype.bindTransformFeedback = function (value) {
  12101. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12102. };
  12103. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12104. if (usePoints === void 0) { usePoints = true; }
  12105. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12106. };
  12107. Engine.prototype.endTransformFeedback = function () {
  12108. this._gl.endTransformFeedback();
  12109. };
  12110. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12111. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12112. };
  12113. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12114. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12115. };
  12116. // Statics
  12117. Engine.isSupported = function () {
  12118. try {
  12119. var tempcanvas = document.createElement("canvas");
  12120. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12121. return gl != null && !!window.WebGLRenderingContext;
  12122. }
  12123. catch (e) {
  12124. return false;
  12125. }
  12126. };
  12127. Engine.Instances = new Array();
  12128. // Const statics
  12129. Engine._ALPHA_DISABLE = 0;
  12130. Engine._ALPHA_ADD = 1;
  12131. Engine._ALPHA_COMBINE = 2;
  12132. Engine._ALPHA_SUBTRACT = 3;
  12133. Engine._ALPHA_MULTIPLY = 4;
  12134. Engine._ALPHA_MAXIMIZED = 5;
  12135. Engine._ALPHA_ONEONE = 6;
  12136. Engine._ALPHA_PREMULTIPLIED = 7;
  12137. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12138. Engine._ALPHA_INTERPOLATE = 9;
  12139. Engine._ALPHA_SCREENMODE = 10;
  12140. Engine._DELAYLOADSTATE_NONE = 0;
  12141. Engine._DELAYLOADSTATE_LOADED = 1;
  12142. Engine._DELAYLOADSTATE_LOADING = 2;
  12143. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12144. Engine._TEXTUREFORMAT_ALPHA = 0;
  12145. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12146. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12147. Engine._TEXTUREFORMAT_RGB = 4;
  12148. Engine._TEXTUREFORMAT_RGBA = 5;
  12149. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12150. Engine._TEXTURETYPE_FLOAT = 1;
  12151. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12152. // Depht or Stencil test Constants.
  12153. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12154. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  12155. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  12156. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  12157. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  12158. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  12159. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  12160. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  12161. // Stencil Actions Constants.
  12162. Engine._KEEP = 0x1E00;
  12163. Engine._REPLACE = 0x1E01;
  12164. Engine._INCR = 0x1E02;
  12165. Engine._DECR = 0x1E03;
  12166. Engine._INVERT = 0x150A;
  12167. Engine._INCR_WRAP = 0x8507;
  12168. Engine._DECR_WRAP = 0x8508;
  12169. // Texture rescaling mode
  12170. Engine._SCALEMODE_FLOOR = 1;
  12171. Engine._SCALEMODE_NEAREST = 2;
  12172. Engine._SCALEMODE_CEILING = 3;
  12173. // Updatable statics so stick with vars here
  12174. Engine.CollisionsEpsilon = 0.001;
  12175. Engine.CodeRepository = "src/";
  12176. Engine.ShadersRepository = "src/Shaders/";
  12177. return Engine;
  12178. }());
  12179. BABYLON.Engine = Engine;
  12180. })(BABYLON || (BABYLON = {}));
  12181. //# sourceMappingURL=babylon.engine.js.map
  12182. var BABYLON;
  12183. (function (BABYLON) {
  12184. /**
  12185. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12186. */
  12187. var Node = /** @class */ (function () {
  12188. /**
  12189. * @constructor
  12190. * @param {string} name - the name and id to be given to this node
  12191. * @param {BABYLON.Scene} the scene this node will be added to
  12192. */
  12193. function Node(name, scene) {
  12194. if (scene === void 0) { scene = null; }
  12195. this.state = "";
  12196. this.metadata = null;
  12197. this.doNotSerialize = false;
  12198. this.animations = new Array();
  12199. this._ranges = {};
  12200. this._isEnabled = true;
  12201. this._isReady = true;
  12202. this._currentRenderId = -1;
  12203. this._parentRenderId = -1;
  12204. /**
  12205. * An event triggered when the mesh is disposed.
  12206. * @type {BABYLON.Observable}
  12207. */
  12208. this.onDisposeObservable = new BABYLON.Observable();
  12209. // Behaviors
  12210. this._behaviors = new Array();
  12211. this.name = name;
  12212. this.id = name;
  12213. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12214. this.uniqueId = this._scene.getUniqueId();
  12215. this._initCache();
  12216. }
  12217. Object.defineProperty(Node.prototype, "parent", {
  12218. get: function () {
  12219. return this._parentNode;
  12220. },
  12221. set: function (parent) {
  12222. if (this._parentNode === parent) {
  12223. return;
  12224. }
  12225. if (this._parentNode) {
  12226. var index = this._parentNode._children.indexOf(this);
  12227. if (index !== -1) {
  12228. this._parentNode._children.splice(index, 1);
  12229. }
  12230. }
  12231. this._parentNode = parent;
  12232. if (this._parentNode) {
  12233. if (!this._parentNode._children) {
  12234. this._parentNode._children = new Array();
  12235. }
  12236. this._parentNode._children.push(this);
  12237. }
  12238. },
  12239. enumerable: true,
  12240. configurable: true
  12241. });
  12242. Node.prototype.getClassName = function () {
  12243. return "Node";
  12244. };
  12245. Object.defineProperty(Node.prototype, "onDispose", {
  12246. set: function (callback) {
  12247. if (this._onDisposeObserver) {
  12248. this.onDisposeObservable.remove(this._onDisposeObserver);
  12249. }
  12250. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12251. },
  12252. enumerable: true,
  12253. configurable: true
  12254. });
  12255. Node.prototype.getScene = function () {
  12256. return this._scene;
  12257. };
  12258. Node.prototype.getEngine = function () {
  12259. return this._scene.getEngine();
  12260. };
  12261. Node.prototype.addBehavior = function (behavior) {
  12262. var _this = this;
  12263. var index = this._behaviors.indexOf(behavior);
  12264. if (index !== -1) {
  12265. return this;
  12266. }
  12267. behavior.init();
  12268. if (this._scene.isLoading) {
  12269. // We defer the attach when the scene will be loaded
  12270. var observer = this._scene.onDataLoadedObservable.add(function () {
  12271. behavior.attach(_this);
  12272. _this._scene.onDataLoadedObservable.remove(observer);
  12273. });
  12274. }
  12275. else {
  12276. behavior.attach(this);
  12277. }
  12278. this._behaviors.push(behavior);
  12279. return this;
  12280. };
  12281. Node.prototype.removeBehavior = function (behavior) {
  12282. var index = this._behaviors.indexOf(behavior);
  12283. if (index === -1) {
  12284. return this;
  12285. }
  12286. this._behaviors[index].detach();
  12287. this._behaviors.splice(index, 1);
  12288. return this;
  12289. };
  12290. Object.defineProperty(Node.prototype, "behaviors", {
  12291. get: function () {
  12292. return this._behaviors;
  12293. },
  12294. enumerable: true,
  12295. configurable: true
  12296. });
  12297. Node.prototype.getBehaviorByName = function (name) {
  12298. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12299. var behavior = _a[_i];
  12300. if (behavior.name === name) {
  12301. return behavior;
  12302. }
  12303. }
  12304. return null;
  12305. };
  12306. // override it in derived class
  12307. Node.prototype.getWorldMatrix = function () {
  12308. return BABYLON.Matrix.Identity();
  12309. };
  12310. // override it in derived class if you add new variables to the cache
  12311. // and call the parent class method
  12312. Node.prototype._initCache = function () {
  12313. this._cache = {};
  12314. this._cache.parent = undefined;
  12315. };
  12316. Node.prototype.updateCache = function (force) {
  12317. if (!force && this.isSynchronized())
  12318. return;
  12319. this._cache.parent = this.parent;
  12320. this._updateCache();
  12321. };
  12322. // override it in derived class if you add new variables to the cache
  12323. // and call the parent class method if !ignoreParentClass
  12324. Node.prototype._updateCache = function (ignoreParentClass) {
  12325. };
  12326. // override it in derived class if you add new variables to the cache
  12327. Node.prototype._isSynchronized = function () {
  12328. return true;
  12329. };
  12330. Node.prototype._markSyncedWithParent = function () {
  12331. if (this.parent) {
  12332. this._parentRenderId = this.parent._currentRenderId;
  12333. }
  12334. };
  12335. Node.prototype.isSynchronizedWithParent = function () {
  12336. if (!this.parent) {
  12337. return true;
  12338. }
  12339. if (this._parentRenderId !== this.parent._currentRenderId) {
  12340. return false;
  12341. }
  12342. return this.parent.isSynchronized();
  12343. };
  12344. Node.prototype.isSynchronized = function (updateCache) {
  12345. var check = this.hasNewParent();
  12346. check = check || !this.isSynchronizedWithParent();
  12347. check = check || !this._isSynchronized();
  12348. if (updateCache)
  12349. this.updateCache(true);
  12350. return !check;
  12351. };
  12352. Node.prototype.hasNewParent = function (update) {
  12353. if (this._cache.parent === this.parent)
  12354. return false;
  12355. if (update)
  12356. this._cache.parent = this.parent;
  12357. return true;
  12358. };
  12359. /**
  12360. * Is this node ready to be used/rendered
  12361. * @return {boolean} is it ready
  12362. */
  12363. Node.prototype.isReady = function () {
  12364. return this._isReady;
  12365. };
  12366. /**
  12367. * Is this node enabled.
  12368. * If the node has a parent and is enabled, the parent will be inspected as well.
  12369. * @return {boolean} whether this node (and its parent) is enabled.
  12370. * @see setEnabled
  12371. */
  12372. Node.prototype.isEnabled = function () {
  12373. if (!this._isEnabled) {
  12374. return false;
  12375. }
  12376. if (this.parent) {
  12377. return this.parent.isEnabled();
  12378. }
  12379. return true;
  12380. };
  12381. /**
  12382. * Set the enabled state of this node.
  12383. * @param {boolean} value - the new enabled state
  12384. * @see isEnabled
  12385. */
  12386. Node.prototype.setEnabled = function (value) {
  12387. this._isEnabled = value;
  12388. };
  12389. /**
  12390. * Is this node a descendant of the given node.
  12391. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12392. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12393. * @see parent
  12394. */
  12395. Node.prototype.isDescendantOf = function (ancestor) {
  12396. if (this.parent) {
  12397. if (this.parent === ancestor) {
  12398. return true;
  12399. }
  12400. return this.parent.isDescendantOf(ancestor);
  12401. }
  12402. return false;
  12403. };
  12404. /**
  12405. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12406. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12407. * @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.
  12408. * @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.
  12409. */
  12410. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12411. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12412. if (!this._children) {
  12413. return;
  12414. }
  12415. for (var index = 0; index < this._children.length; index++) {
  12416. var item = this._children[index];
  12417. if (!predicate || predicate(item)) {
  12418. results.push(item);
  12419. }
  12420. if (!directDescendantsOnly) {
  12421. item._getDescendants(results, false, predicate);
  12422. }
  12423. }
  12424. };
  12425. /**
  12426. * Will return all nodes that have this node as ascendant.
  12427. * @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.
  12428. * @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.
  12429. * @return {BABYLON.Node[]} all children nodes of all types.
  12430. */
  12431. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12432. var results = new Array();
  12433. this._getDescendants(results, directDescendantsOnly, predicate);
  12434. return results;
  12435. };
  12436. /**
  12437. * Get all child-meshes of this node.
  12438. */
  12439. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  12440. var results = [];
  12441. this._getDescendants(results, directDecendantsOnly, function (node) {
  12442. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12443. });
  12444. return results;
  12445. };
  12446. /**
  12447. * Get all direct children of this node.
  12448. */
  12449. Node.prototype.getChildren = function (predicate) {
  12450. return this.getDescendants(true, predicate);
  12451. };
  12452. Node.prototype._setReady = function (state) {
  12453. if (state === this._isReady) {
  12454. return;
  12455. }
  12456. if (!state) {
  12457. this._isReady = false;
  12458. return;
  12459. }
  12460. this._isReady = true;
  12461. if (this.onReady) {
  12462. this.onReady(this);
  12463. }
  12464. };
  12465. Node.prototype.getAnimationByName = function (name) {
  12466. for (var i = 0; i < this.animations.length; i++) {
  12467. var animation = this.animations[i];
  12468. if (animation.name === name) {
  12469. return animation;
  12470. }
  12471. }
  12472. return null;
  12473. };
  12474. Node.prototype.createAnimationRange = function (name, from, to) {
  12475. // check name not already in use
  12476. if (!this._ranges[name]) {
  12477. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  12478. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12479. if (this.animations[i]) {
  12480. this.animations[i].createRange(name, from, to);
  12481. }
  12482. }
  12483. }
  12484. };
  12485. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  12486. if (deleteFrames === void 0) { deleteFrames = true; }
  12487. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  12488. if (this.animations[i]) {
  12489. this.animations[i].deleteRange(name, deleteFrames);
  12490. }
  12491. }
  12492. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  12493. };
  12494. Node.prototype.getAnimationRange = function (name) {
  12495. return this._ranges[name];
  12496. };
  12497. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  12498. var range = this.getAnimationRange(name);
  12499. if (!range) {
  12500. return;
  12501. }
  12502. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  12503. };
  12504. Node.prototype.serializeAnimationRanges = function () {
  12505. var serializationRanges = [];
  12506. for (var name in this._ranges) {
  12507. var localRange = this._ranges[name];
  12508. if (!localRange) {
  12509. continue;
  12510. }
  12511. var range = {};
  12512. range.name = name;
  12513. range.from = localRange.from;
  12514. range.to = localRange.to;
  12515. serializationRanges.push(range);
  12516. }
  12517. return serializationRanges;
  12518. };
  12519. Node.prototype.dispose = function () {
  12520. this.parent = null;
  12521. // Callback
  12522. this.onDisposeObservable.notifyObservers(this);
  12523. this.onDisposeObservable.clear();
  12524. // Behaviors
  12525. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12526. var behavior = _a[_i];
  12527. behavior.detach();
  12528. }
  12529. this._behaviors = [];
  12530. };
  12531. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  12532. if (parsedNode.ranges) {
  12533. for (var index = 0; index < parsedNode.ranges.length; index++) {
  12534. var data = parsedNode.ranges[index];
  12535. node.createAnimationRange(data.name, data.from, data.to);
  12536. }
  12537. }
  12538. };
  12539. __decorate([
  12540. BABYLON.serialize()
  12541. ], Node.prototype, "name", void 0);
  12542. __decorate([
  12543. BABYLON.serialize()
  12544. ], Node.prototype, "id", void 0);
  12545. __decorate([
  12546. BABYLON.serialize()
  12547. ], Node.prototype, "uniqueId", void 0);
  12548. __decorate([
  12549. BABYLON.serialize()
  12550. ], Node.prototype, "state", void 0);
  12551. __decorate([
  12552. BABYLON.serialize()
  12553. ], Node.prototype, "metadata", void 0);
  12554. return Node;
  12555. }());
  12556. BABYLON.Node = Node;
  12557. })(BABYLON || (BABYLON = {}));
  12558. //# sourceMappingURL=babylon.node.js.map
  12559. var BABYLON;
  12560. (function (BABYLON) {
  12561. var BoundingSphere = /** @class */ (function () {
  12562. function BoundingSphere(minimum, maximum) {
  12563. this.minimum = minimum;
  12564. this.maximum = maximum;
  12565. this._tempRadiusVector = BABYLON.Vector3.Zero();
  12566. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  12567. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  12568. this.radius = distance * 0.5;
  12569. this.centerWorld = BABYLON.Vector3.Zero();
  12570. this._update(BABYLON.Matrix.Identity());
  12571. }
  12572. // Methods
  12573. BoundingSphere.prototype._update = function (world) {
  12574. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  12575. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  12576. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  12577. };
  12578. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  12579. for (var i = 0; i < 6; i++) {
  12580. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  12581. return false;
  12582. }
  12583. return true;
  12584. };
  12585. BoundingSphere.prototype.intersectsPoint = function (point) {
  12586. var x = this.centerWorld.x - point.x;
  12587. var y = this.centerWorld.y - point.y;
  12588. var z = this.centerWorld.z - point.z;
  12589. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12590. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  12591. return false;
  12592. return true;
  12593. };
  12594. // Statics
  12595. BoundingSphere.Intersects = function (sphere0, sphere1) {
  12596. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  12597. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  12598. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  12599. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  12600. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  12601. return false;
  12602. return true;
  12603. };
  12604. return BoundingSphere;
  12605. }());
  12606. BABYLON.BoundingSphere = BoundingSphere;
  12607. })(BABYLON || (BABYLON = {}));
  12608. //# sourceMappingURL=babylon.boundingSphere.js.map
  12609. var BABYLON;
  12610. (function (BABYLON) {
  12611. var BoundingBox = /** @class */ (function () {
  12612. function BoundingBox(minimum, maximum) {
  12613. this.minimum = minimum;
  12614. this.maximum = maximum;
  12615. this.vectors = new Array();
  12616. this.vectorsWorld = new Array();
  12617. // Bounding vectors
  12618. this.vectors.push(this.minimum.clone());
  12619. this.vectors.push(this.maximum.clone());
  12620. this.vectors.push(this.minimum.clone());
  12621. this.vectors[2].x = this.maximum.x;
  12622. this.vectors.push(this.minimum.clone());
  12623. this.vectors[3].y = this.maximum.y;
  12624. this.vectors.push(this.minimum.clone());
  12625. this.vectors[4].z = this.maximum.z;
  12626. this.vectors.push(this.maximum.clone());
  12627. this.vectors[5].z = this.minimum.z;
  12628. this.vectors.push(this.maximum.clone());
  12629. this.vectors[6].x = this.minimum.x;
  12630. this.vectors.push(this.maximum.clone());
  12631. this.vectors[7].y = this.minimum.y;
  12632. // OBB
  12633. this.center = this.maximum.add(this.minimum).scale(0.5);
  12634. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  12635. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  12636. // World
  12637. for (var index = 0; index < this.vectors.length; index++) {
  12638. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  12639. }
  12640. this.minimumWorld = BABYLON.Vector3.Zero();
  12641. this.maximumWorld = BABYLON.Vector3.Zero();
  12642. this.centerWorld = BABYLON.Vector3.Zero();
  12643. this.extendSizeWorld = BABYLON.Vector3.Zero();
  12644. this._update(BABYLON.Matrix.Identity());
  12645. }
  12646. // Methods
  12647. BoundingBox.prototype.getWorldMatrix = function () {
  12648. return this._worldMatrix;
  12649. };
  12650. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  12651. this._worldMatrix.copyFrom(matrix);
  12652. return this;
  12653. };
  12654. BoundingBox.prototype._update = function (world) {
  12655. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  12656. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  12657. for (var index = 0; index < this.vectors.length; index++) {
  12658. var v = this.vectorsWorld[index];
  12659. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  12660. if (v.x < this.minimumWorld.x)
  12661. this.minimumWorld.x = v.x;
  12662. if (v.y < this.minimumWorld.y)
  12663. this.minimumWorld.y = v.y;
  12664. if (v.z < this.minimumWorld.z)
  12665. this.minimumWorld.z = v.z;
  12666. if (v.x > this.maximumWorld.x)
  12667. this.maximumWorld.x = v.x;
  12668. if (v.y > this.maximumWorld.y)
  12669. this.maximumWorld.y = v.y;
  12670. if (v.z > this.maximumWorld.z)
  12671. this.maximumWorld.z = v.z;
  12672. }
  12673. // Extend
  12674. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  12675. this.extendSizeWorld.scaleInPlace(0.5);
  12676. // OBB
  12677. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  12678. this.centerWorld.scaleInPlace(0.5);
  12679. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  12680. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  12681. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  12682. this._worldMatrix = world;
  12683. };
  12684. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  12685. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  12686. };
  12687. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12688. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  12689. };
  12690. BoundingBox.prototype.intersectsPoint = function (point) {
  12691. var delta = -BABYLON.Epsilon;
  12692. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  12693. return false;
  12694. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  12695. return false;
  12696. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  12697. return false;
  12698. return true;
  12699. };
  12700. BoundingBox.prototype.intersectsSphere = function (sphere) {
  12701. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  12702. };
  12703. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  12704. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  12705. return false;
  12706. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  12707. return false;
  12708. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  12709. return false;
  12710. return true;
  12711. };
  12712. // Statics
  12713. BoundingBox.Intersects = function (box0, box1) {
  12714. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  12715. return false;
  12716. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  12717. return false;
  12718. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  12719. return false;
  12720. return true;
  12721. };
  12722. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  12723. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  12724. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  12725. return (num <= (sphereRadius * sphereRadius));
  12726. };
  12727. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  12728. for (var p = 0; p < 6; p++) {
  12729. for (var i = 0; i < 8; i++) {
  12730. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12731. return false;
  12732. }
  12733. }
  12734. }
  12735. return true;
  12736. };
  12737. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  12738. for (var p = 0; p < 6; p++) {
  12739. var inCount = 8;
  12740. for (var i = 0; i < 8; i++) {
  12741. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  12742. --inCount;
  12743. }
  12744. else {
  12745. break;
  12746. }
  12747. }
  12748. if (inCount === 0)
  12749. return false;
  12750. }
  12751. return true;
  12752. };
  12753. return BoundingBox;
  12754. }());
  12755. BABYLON.BoundingBox = BoundingBox;
  12756. })(BABYLON || (BABYLON = {}));
  12757. //# sourceMappingURL=babylon.boundingBox.js.map
  12758. var BABYLON;
  12759. (function (BABYLON) {
  12760. var computeBoxExtents = function (axis, box) {
  12761. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  12762. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  12763. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  12764. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  12765. var r = r0 + r1 + r2;
  12766. return {
  12767. min: p - r,
  12768. max: p + r
  12769. };
  12770. };
  12771. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  12772. var axisOverlap = function (axis, box0, box1) {
  12773. var result0 = computeBoxExtents(axis, box0);
  12774. var result1 = computeBoxExtents(axis, box1);
  12775. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  12776. };
  12777. var BoundingInfo = /** @class */ (function () {
  12778. function BoundingInfo(minimum, maximum) {
  12779. this.minimum = minimum;
  12780. this.maximum = maximum;
  12781. this._isLocked = false;
  12782. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  12783. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  12784. }
  12785. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  12786. get: function () {
  12787. return this._isLocked;
  12788. },
  12789. set: function (value) {
  12790. this._isLocked = value;
  12791. },
  12792. enumerable: true,
  12793. configurable: true
  12794. });
  12795. // Methods
  12796. BoundingInfo.prototype.update = function (world) {
  12797. if (this._isLocked) {
  12798. return;
  12799. }
  12800. this.boundingBox._update(world);
  12801. this.boundingSphere._update(world);
  12802. };
  12803. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  12804. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  12805. return false;
  12806. return this.boundingBox.isInFrustum(frustumPlanes);
  12807. };
  12808. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  12809. /**
  12810. * Gets the world distance between the min and max points of the bounding box
  12811. */
  12812. get: function () {
  12813. var boundingBox = this.boundingBox;
  12814. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  12815. return size.length();
  12816. },
  12817. enumerable: true,
  12818. configurable: true
  12819. });
  12820. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  12821. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  12822. };
  12823. BoundingInfo.prototype._checkCollision = function (collider) {
  12824. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  12825. };
  12826. BoundingInfo.prototype.intersectsPoint = function (point) {
  12827. if (!this.boundingSphere.centerWorld) {
  12828. return false;
  12829. }
  12830. if (!this.boundingSphere.intersectsPoint(point)) {
  12831. return false;
  12832. }
  12833. if (!this.boundingBox.intersectsPoint(point)) {
  12834. return false;
  12835. }
  12836. return true;
  12837. };
  12838. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  12839. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  12840. return false;
  12841. }
  12842. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  12843. return false;
  12844. }
  12845. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  12846. return false;
  12847. }
  12848. if (!precise) {
  12849. return true;
  12850. }
  12851. var box0 = this.boundingBox;
  12852. var box1 = boundingInfo.boundingBox;
  12853. if (!axisOverlap(box0.directions[0], box0, box1))
  12854. return false;
  12855. if (!axisOverlap(box0.directions[1], box0, box1))
  12856. return false;
  12857. if (!axisOverlap(box0.directions[2], box0, box1))
  12858. return false;
  12859. if (!axisOverlap(box1.directions[0], box0, box1))
  12860. return false;
  12861. if (!axisOverlap(box1.directions[1], box0, box1))
  12862. return false;
  12863. if (!axisOverlap(box1.directions[2], box0, box1))
  12864. return false;
  12865. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  12866. return false;
  12867. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  12868. return false;
  12869. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  12870. return false;
  12871. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  12872. return false;
  12873. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  12874. return false;
  12875. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  12876. return false;
  12877. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  12878. return false;
  12879. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  12880. return false;
  12881. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  12882. return false;
  12883. return true;
  12884. };
  12885. return BoundingInfo;
  12886. }());
  12887. BABYLON.BoundingInfo = BoundingInfo;
  12888. })(BABYLON || (BABYLON = {}));
  12889. //# sourceMappingURL=babylon.boundingInfo.js.map
  12890. var BABYLON;
  12891. (function (BABYLON) {
  12892. var AbstractMesh = /** @class */ (function (_super) {
  12893. __extends(AbstractMesh, _super);
  12894. // Constructor
  12895. function AbstractMesh(name, scene) {
  12896. if (scene === void 0) { scene = null; }
  12897. var _this = _super.call(this, name, scene) || this;
  12898. _this._facetNb = 0; // facet number
  12899. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  12900. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  12901. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  12902. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  12903. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  12904. _this._subDiv = {
  12905. max: 1,
  12906. X: 1,
  12907. Y: 1,
  12908. Z: 1
  12909. };
  12910. // Normal matrix
  12911. _this._nonUniformScaling = false;
  12912. // Events
  12913. /**
  12914. * An event triggered when this mesh collides with another one
  12915. * @type {BABYLON.Observable}
  12916. */
  12917. _this.onCollideObservable = new BABYLON.Observable();
  12918. /**
  12919. * An event triggered when the collision's position changes
  12920. * @type {BABYLON.Observable}
  12921. */
  12922. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  12923. /**
  12924. * An event triggered after the world matrix is updated
  12925. * @type {BABYLON.Observable}
  12926. */
  12927. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  12928. /**
  12929. * An event triggered when material is changed
  12930. * @type {BABYLON.Observable}
  12931. */
  12932. _this.onMaterialChangedObservable = new BABYLON.Observable();
  12933. // Properties
  12934. _this.definedFacingForward = true; // orientation for POV movement & rotation
  12935. _this.position = BABYLON.Vector3.Zero();
  12936. /**
  12937. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  12938. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  12939. * or
  12940. * 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.
  12941. * for more info check WebGl documentations
  12942. */
  12943. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  12944. /**
  12945. * 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:
  12946. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  12947. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  12948. * 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.
  12949. */
  12950. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  12951. /**
  12952. * 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.
  12953. * The default value is -1 which means don't break the query and wait till the result.
  12954. */
  12955. _this.occlusionRetryCount = -1;
  12956. _this._occlusionInternalRetryCounter = 0;
  12957. _this._isOccluded = false;
  12958. _this._isOcclusionQueryInProgress = false;
  12959. _this._rotation = BABYLON.Vector3.Zero();
  12960. _this._scaling = BABYLON.Vector3.One();
  12961. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  12962. _this.visibility = 1.0;
  12963. _this.alphaIndex = Number.MAX_VALUE;
  12964. _this.infiniteDistance = false;
  12965. _this.isVisible = true;
  12966. _this.isPickable = true;
  12967. _this.showBoundingBox = false;
  12968. _this.showSubMeshesBoundingBox = false;
  12969. _this.isBlocker = false;
  12970. _this.enablePointerMoveEvents = false;
  12971. _this.renderingGroupId = 0;
  12972. _this._receiveShadows = false;
  12973. _this.renderOutline = false;
  12974. _this.outlineColor = BABYLON.Color3.Red();
  12975. _this.outlineWidth = 0.02;
  12976. _this.renderOverlay = false;
  12977. _this.overlayColor = BABYLON.Color3.Red();
  12978. _this.overlayAlpha = 0.5;
  12979. _this._hasVertexAlpha = false;
  12980. _this._useVertexColors = true;
  12981. _this._computeBonesUsingShaders = true;
  12982. _this._numBoneInfluencers = 4;
  12983. _this._applyFog = true;
  12984. _this.scalingDeterminant = 1;
  12985. _this.useOctreeForRenderingSelection = true;
  12986. _this.useOctreeForPicking = true;
  12987. _this.useOctreeForCollisions = true;
  12988. _this._layerMask = 0x0FFFFFFF;
  12989. /**
  12990. * True if the mesh must be rendered in any case.
  12991. */
  12992. _this.alwaysSelectAsActiveMesh = false;
  12993. // Collisions
  12994. _this._checkCollisions = false;
  12995. _this._collisionMask = -1;
  12996. _this._collisionGroup = -1;
  12997. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  12998. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  12999. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  13000. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  13001. // Edges
  13002. _this.edgesWidth = 1;
  13003. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  13004. // Cache
  13005. _this._localWorld = BABYLON.Matrix.Zero();
  13006. _this._worldMatrix = BABYLON.Matrix.Zero();
  13007. _this._absolutePosition = BABYLON.Vector3.Zero();
  13008. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  13009. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  13010. _this._isDirty = false;
  13011. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13012. _this._postMultiplyPivotMatrix = false;
  13013. _this._isDisposed = false;
  13014. _this._renderId = 0;
  13015. _this._intersectionsInProgress = new Array();
  13016. _this._isWorldMatrixFrozen = false;
  13017. _this._unIndexed = false;
  13018. _this._lightSources = new Array();
  13019. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  13020. if (collidedMesh === void 0) { collidedMesh = null; }
  13021. //TODO move this to the collision coordinator!
  13022. if (_this.getScene().workerCollisions)
  13023. newPosition.multiplyInPlace(_this._collider.radius);
  13024. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  13025. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  13026. _this.position.addInPlace(_this._diffPositionForCollisions);
  13027. }
  13028. if (collidedMesh) {
  13029. _this.onCollideObservable.notifyObservers(collidedMesh);
  13030. }
  13031. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  13032. };
  13033. _this.getScene().addMesh(_this);
  13034. _this._resyncLightSources();
  13035. return _this;
  13036. }
  13037. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  13038. get: function () {
  13039. return AbstractMesh._BILLBOARDMODE_NONE;
  13040. },
  13041. enumerable: true,
  13042. configurable: true
  13043. });
  13044. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  13045. get: function () {
  13046. return AbstractMesh._BILLBOARDMODE_X;
  13047. },
  13048. enumerable: true,
  13049. configurable: true
  13050. });
  13051. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  13052. get: function () {
  13053. return AbstractMesh._BILLBOARDMODE_Y;
  13054. },
  13055. enumerable: true,
  13056. configurable: true
  13057. });
  13058. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  13059. get: function () {
  13060. return AbstractMesh._BILLBOARDMODE_Z;
  13061. },
  13062. enumerable: true,
  13063. configurable: true
  13064. });
  13065. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  13066. get: function () {
  13067. return AbstractMesh._BILLBOARDMODE_ALL;
  13068. },
  13069. enumerable: true,
  13070. configurable: true
  13071. });
  13072. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  13073. /**
  13074. * Read-only : the number of facets in the mesh
  13075. */
  13076. get: function () {
  13077. return this._facetNb;
  13078. },
  13079. enumerable: true,
  13080. configurable: true
  13081. });
  13082. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  13083. /**
  13084. * The number (integer) of subdivisions per axis in the partioning space
  13085. */
  13086. get: function () {
  13087. return this._partitioningSubdivisions;
  13088. },
  13089. set: function (nb) {
  13090. this._partitioningSubdivisions = nb;
  13091. },
  13092. enumerable: true,
  13093. configurable: true
  13094. });
  13095. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  13096. /**
  13097. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  13098. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  13099. */
  13100. get: function () {
  13101. return this._partitioningBBoxRatio;
  13102. },
  13103. set: function (ratio) {
  13104. this._partitioningBBoxRatio = ratio;
  13105. },
  13106. enumerable: true,
  13107. configurable: true
  13108. });
  13109. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  13110. /**
  13111. * Read-only boolean : is the feature facetData enabled ?
  13112. */
  13113. get: function () {
  13114. return this._facetDataEnabled;
  13115. },
  13116. enumerable: true,
  13117. configurable: true
  13118. });
  13119. Object.defineProperty(AbstractMesh.prototype, "nonUniformScaling", {
  13120. get: function () {
  13121. return this._nonUniformScaling;
  13122. },
  13123. set: function (value) {
  13124. if (this._nonUniformScaling === value) {
  13125. return;
  13126. }
  13127. this._nonUniformScaling = true;
  13128. this._markSubMeshesAsMiscDirty();
  13129. },
  13130. enumerable: true,
  13131. configurable: true
  13132. });
  13133. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  13134. set: function (callback) {
  13135. if (this._onCollideObserver) {
  13136. this.onCollideObservable.remove(this._onCollideObserver);
  13137. }
  13138. this._onCollideObserver = this.onCollideObservable.add(callback);
  13139. },
  13140. enumerable: true,
  13141. configurable: true
  13142. });
  13143. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  13144. set: function (callback) {
  13145. if (this._onCollisionPositionChangeObserver) {
  13146. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  13147. }
  13148. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  13149. },
  13150. enumerable: true,
  13151. configurable: true
  13152. });
  13153. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  13154. /**
  13155. * 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.
  13156. */
  13157. get: function () {
  13158. return this._isOccluded;
  13159. },
  13160. set: function (value) {
  13161. this._isOccluded = value;
  13162. },
  13163. enumerable: true,
  13164. configurable: true
  13165. });
  13166. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  13167. /**
  13168. * Flag to check the progress status of the query
  13169. */
  13170. get: function () {
  13171. return this._isOcclusionQueryInProgress;
  13172. },
  13173. enumerable: true,
  13174. configurable: true
  13175. });
  13176. Object.defineProperty(AbstractMesh.prototype, "material", {
  13177. get: function () {
  13178. return this._material;
  13179. },
  13180. set: function (value) {
  13181. if (this._material === value) {
  13182. return;
  13183. }
  13184. this._material = value;
  13185. if (this.onMaterialChangedObservable.hasObservers) {
  13186. this.onMaterialChangedObservable.notifyObservers(this);
  13187. }
  13188. if (!this.subMeshes) {
  13189. return;
  13190. }
  13191. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13192. var subMesh = _a[_i];
  13193. subMesh.setEffect(null);
  13194. }
  13195. },
  13196. enumerable: true,
  13197. configurable: true
  13198. });
  13199. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  13200. get: function () {
  13201. return this._receiveShadows;
  13202. },
  13203. set: function (value) {
  13204. if (this._receiveShadows === value) {
  13205. return;
  13206. }
  13207. this._receiveShadows = value;
  13208. this._markSubMeshesAsLightDirty();
  13209. },
  13210. enumerable: true,
  13211. configurable: true
  13212. });
  13213. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  13214. get: function () {
  13215. return this._hasVertexAlpha;
  13216. },
  13217. set: function (value) {
  13218. if (this._hasVertexAlpha === value) {
  13219. return;
  13220. }
  13221. this._hasVertexAlpha = value;
  13222. this._markSubMeshesAsAttributesDirty();
  13223. },
  13224. enumerable: true,
  13225. configurable: true
  13226. });
  13227. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  13228. get: function () {
  13229. return this._useVertexColors;
  13230. },
  13231. set: function (value) {
  13232. if (this._useVertexColors === value) {
  13233. return;
  13234. }
  13235. this._useVertexColors = value;
  13236. this._markSubMeshesAsAttributesDirty();
  13237. },
  13238. enumerable: true,
  13239. configurable: true
  13240. });
  13241. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  13242. get: function () {
  13243. return this._computeBonesUsingShaders;
  13244. },
  13245. set: function (value) {
  13246. if (this._computeBonesUsingShaders === value) {
  13247. return;
  13248. }
  13249. this._computeBonesUsingShaders = value;
  13250. this._markSubMeshesAsAttributesDirty();
  13251. },
  13252. enumerable: true,
  13253. configurable: true
  13254. });
  13255. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  13256. get: function () {
  13257. return this._numBoneInfluencers;
  13258. },
  13259. set: function (value) {
  13260. if (this._numBoneInfluencers === value) {
  13261. return;
  13262. }
  13263. this._numBoneInfluencers = value;
  13264. this._markSubMeshesAsAttributesDirty();
  13265. },
  13266. enumerable: true,
  13267. configurable: true
  13268. });
  13269. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  13270. get: function () {
  13271. return this._applyFog;
  13272. },
  13273. set: function (value) {
  13274. if (this._applyFog === value) {
  13275. return;
  13276. }
  13277. this._applyFog = value;
  13278. this._markSubMeshesAsMiscDirty();
  13279. },
  13280. enumerable: true,
  13281. configurable: true
  13282. });
  13283. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  13284. get: function () {
  13285. return this._layerMask;
  13286. },
  13287. set: function (value) {
  13288. if (value === this._layerMask) {
  13289. return;
  13290. }
  13291. this._layerMask = value;
  13292. this._resyncLightSources();
  13293. },
  13294. enumerable: true,
  13295. configurable: true
  13296. });
  13297. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  13298. get: function () {
  13299. return this._collisionMask;
  13300. },
  13301. set: function (mask) {
  13302. this._collisionMask = !isNaN(mask) ? mask : -1;
  13303. },
  13304. enumerable: true,
  13305. configurable: true
  13306. });
  13307. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  13308. get: function () {
  13309. return this._collisionGroup;
  13310. },
  13311. set: function (mask) {
  13312. this._collisionGroup = !isNaN(mask) ? mask : -1;
  13313. },
  13314. enumerable: true,
  13315. configurable: true
  13316. });
  13317. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  13318. get: function () {
  13319. return null;
  13320. },
  13321. enumerable: true,
  13322. configurable: true
  13323. });
  13324. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  13325. get: function () {
  13326. return this._skeleton;
  13327. },
  13328. set: function (value) {
  13329. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  13330. this._skeleton._unregisterMeshWithPoseMatrix(this);
  13331. }
  13332. if (value && value.needInitialSkinMatrix) {
  13333. value._registerMeshWithPoseMatrix(this);
  13334. }
  13335. this._skeleton = value;
  13336. if (!this._skeleton) {
  13337. this._bonesTransformMatrices = null;
  13338. }
  13339. this._markSubMeshesAsAttributesDirty();
  13340. },
  13341. enumerable: true,
  13342. configurable: true
  13343. });
  13344. /**
  13345. * Boolean : true if the mesh has been disposed.
  13346. */
  13347. AbstractMesh.prototype.isDisposed = function () {
  13348. return this._isDisposed;
  13349. };
  13350. /**
  13351. * Returns the string "AbstractMesh"
  13352. */
  13353. AbstractMesh.prototype.getClassName = function () {
  13354. return "AbstractMesh";
  13355. };
  13356. /**
  13357. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13358. */
  13359. AbstractMesh.prototype.toString = function (fullDetails) {
  13360. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  13361. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  13362. if (this._skeleton) {
  13363. ret += ", skeleton: " + this._skeleton.name;
  13364. }
  13365. if (fullDetails) {
  13366. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  13367. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  13368. }
  13369. return ret;
  13370. };
  13371. AbstractMesh.prototype._rebuild = function () {
  13372. if (this._occlusionQuery) {
  13373. this._occlusionQuery = null;
  13374. }
  13375. if (this._edgesRenderer) {
  13376. this._edgesRenderer._rebuild();
  13377. }
  13378. if (!this.subMeshes) {
  13379. return;
  13380. }
  13381. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13382. var subMesh = _a[_i];
  13383. subMesh._rebuild();
  13384. }
  13385. };
  13386. AbstractMesh.prototype._resyncLightSources = function () {
  13387. this._lightSources.length = 0;
  13388. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  13389. var light = _a[_i];
  13390. if (!light.isEnabled()) {
  13391. continue;
  13392. }
  13393. if (light.canAffectMesh(this)) {
  13394. this._lightSources.push(light);
  13395. }
  13396. }
  13397. this._markSubMeshesAsLightDirty();
  13398. };
  13399. AbstractMesh.prototype._resyncLighSource = function (light) {
  13400. var isIn = light.isEnabled() && light.canAffectMesh(this);
  13401. var index = this._lightSources.indexOf(light);
  13402. if (index === -1) {
  13403. if (!isIn) {
  13404. return;
  13405. }
  13406. this._lightSources.push(light);
  13407. }
  13408. else {
  13409. if (isIn) {
  13410. return;
  13411. }
  13412. this._lightSources.splice(index, 1);
  13413. }
  13414. this._markSubMeshesAsLightDirty();
  13415. };
  13416. AbstractMesh.prototype._removeLightSource = function (light) {
  13417. var index = this._lightSources.indexOf(light);
  13418. if (index === -1) {
  13419. return;
  13420. }
  13421. this._lightSources.splice(index, 1);
  13422. };
  13423. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  13424. if (!this.subMeshes) {
  13425. return;
  13426. }
  13427. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13428. var subMesh = _a[_i];
  13429. if (subMesh._materialDefines) {
  13430. func(subMesh._materialDefines);
  13431. }
  13432. }
  13433. };
  13434. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  13435. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  13436. };
  13437. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  13438. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  13439. };
  13440. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  13441. if (!this.subMeshes) {
  13442. return;
  13443. }
  13444. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  13445. var subMesh = _a[_i];
  13446. var material = subMesh.getMaterial();
  13447. if (material) {
  13448. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  13449. }
  13450. }
  13451. };
  13452. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  13453. /**
  13454. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13455. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13456. * Default : (0.0, 0.0, 0.0)
  13457. */
  13458. get: function () {
  13459. return this._rotation;
  13460. },
  13461. set: function (newRotation) {
  13462. this._rotation = newRotation;
  13463. },
  13464. enumerable: true,
  13465. configurable: true
  13466. });
  13467. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  13468. /**
  13469. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13470. * Default : (1.0, 1.0, 1.0)
  13471. */
  13472. get: function () {
  13473. return this._scaling;
  13474. },
  13475. set: function (newScaling) {
  13476. this._scaling = newScaling;
  13477. if (this.physicsImpostor) {
  13478. this.physicsImpostor.forceUpdate();
  13479. }
  13480. },
  13481. enumerable: true,
  13482. configurable: true
  13483. });
  13484. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  13485. /**
  13486. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13487. * It's null by default.
  13488. * 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)
  13489. */
  13490. get: function () {
  13491. return this._rotationQuaternion;
  13492. },
  13493. set: function (quaternion) {
  13494. this._rotationQuaternion = quaternion;
  13495. //reset the rotation vector.
  13496. if (quaternion && this.rotation.length()) {
  13497. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13498. }
  13499. },
  13500. enumerable: true,
  13501. configurable: true
  13502. });
  13503. // Methods
  13504. /**
  13505. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13506. * Returns the AbstractMesh.
  13507. */
  13508. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  13509. this._poseMatrix.copyFrom(matrix);
  13510. return this;
  13511. };
  13512. /**
  13513. * Returns the mesh Pose matrix.
  13514. * Returned object : Matrix
  13515. */
  13516. AbstractMesh.prototype.getPoseMatrix = function () {
  13517. return this._poseMatrix;
  13518. };
  13519. /**
  13520. * Disables the mesh edger rendering mode.
  13521. * Returns the AbstractMesh.
  13522. */
  13523. AbstractMesh.prototype.disableEdgesRendering = function () {
  13524. if (this._edgesRenderer) {
  13525. this._edgesRenderer.dispose();
  13526. this._edgesRenderer = null;
  13527. }
  13528. return this;
  13529. };
  13530. /**
  13531. * Enables the edge rendering mode on the mesh.
  13532. * This mode makes the mesh edges visible.
  13533. * Returns the AbstractMesh.
  13534. */
  13535. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  13536. if (epsilon === void 0) { epsilon = 0.95; }
  13537. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  13538. this.disableEdgesRendering();
  13539. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  13540. return this;
  13541. };
  13542. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  13543. /**
  13544. * Returns true if the mesh is blocked. Used by the class Mesh.
  13545. * Returns the boolean `false` by default.
  13546. */
  13547. get: function () {
  13548. return false;
  13549. },
  13550. enumerable: true,
  13551. configurable: true
  13552. });
  13553. /**
  13554. * Returns the mesh itself by default, used by the class Mesh.
  13555. * Returned type : AbstractMesh
  13556. */
  13557. AbstractMesh.prototype.getLOD = function (camera) {
  13558. return this;
  13559. };
  13560. /**
  13561. * Returns 0 by default, used by the class Mesh.
  13562. * Returns an integer.
  13563. */
  13564. AbstractMesh.prototype.getTotalVertices = function () {
  13565. return 0;
  13566. };
  13567. /**
  13568. * Returns null by default, used by the class Mesh.
  13569. * Returned type : integer array
  13570. */
  13571. AbstractMesh.prototype.getIndices = function () {
  13572. return null;
  13573. };
  13574. /**
  13575. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  13576. * Returned type : float array or Float32Array
  13577. */
  13578. AbstractMesh.prototype.getVerticesData = function (kind) {
  13579. return null;
  13580. };
  13581. /**
  13582. * Sets the vertex data of the mesh geometry for the requested `kind`.
  13583. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  13584. * The `data` are either a numeric array either a Float32Array.
  13585. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  13586. * 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).
  13587. * Note that a new underlying VertexBuffer object is created each call.
  13588. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  13589. *
  13590. * Possible `kind` values :
  13591. * - BABYLON.VertexBuffer.PositionKind
  13592. * - BABYLON.VertexBuffer.UVKind
  13593. * - BABYLON.VertexBuffer.UV2Kind
  13594. * - BABYLON.VertexBuffer.UV3Kind
  13595. * - BABYLON.VertexBuffer.UV4Kind
  13596. * - BABYLON.VertexBuffer.UV5Kind
  13597. * - BABYLON.VertexBuffer.UV6Kind
  13598. * - BABYLON.VertexBuffer.ColorKind
  13599. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13600. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13601. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13602. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13603. *
  13604. * Returns the Mesh.
  13605. */
  13606. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  13607. return this;
  13608. };
  13609. /**
  13610. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  13611. * If the mesh has no geometry, it is simply returned as it is.
  13612. * The `data` are either a numeric array either a Float32Array.
  13613. * No new underlying VertexBuffer object is created.
  13614. * 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.
  13615. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  13616. *
  13617. * Possible `kind` values :
  13618. * - BABYLON.VertexBuffer.PositionKind
  13619. * - BABYLON.VertexBuffer.UVKind
  13620. * - BABYLON.VertexBuffer.UV2Kind
  13621. * - BABYLON.VertexBuffer.UV3Kind
  13622. * - BABYLON.VertexBuffer.UV4Kind
  13623. * - BABYLON.VertexBuffer.UV5Kind
  13624. * - BABYLON.VertexBuffer.UV6Kind
  13625. * - BABYLON.VertexBuffer.ColorKind
  13626. * - BABYLON.VertexBuffer.MatricesIndicesKind
  13627. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  13628. * - BABYLON.VertexBuffer.MatricesWeightsKind
  13629. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  13630. *
  13631. * Returns the Mesh.
  13632. */
  13633. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  13634. return this;
  13635. };
  13636. /**
  13637. * Sets the mesh indices.
  13638. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  13639. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  13640. * This method creates a new index buffer each call.
  13641. * Returns the Mesh.
  13642. */
  13643. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  13644. return this;
  13645. };
  13646. /** Returns false by default, used by the class Mesh.
  13647. * Returns a boolean
  13648. */
  13649. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  13650. return false;
  13651. };
  13652. /**
  13653. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  13654. * Returns a BoundingInfo
  13655. */
  13656. AbstractMesh.prototype.getBoundingInfo = function () {
  13657. if (this._masterMesh) {
  13658. return this._masterMesh.getBoundingInfo();
  13659. }
  13660. if (!this._boundingInfo) {
  13661. this._updateBoundingInfo();
  13662. }
  13663. return this._boundingInfo;
  13664. };
  13665. /**
  13666. * Sets a mesh new object BoundingInfo.
  13667. * Returns the AbstractMesh.
  13668. */
  13669. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  13670. this._boundingInfo = boundingInfo;
  13671. return this;
  13672. };
  13673. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  13674. get: function () {
  13675. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  13676. },
  13677. enumerable: true,
  13678. configurable: true
  13679. });
  13680. AbstractMesh.prototype._preActivate = function () {
  13681. };
  13682. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  13683. };
  13684. AbstractMesh.prototype._activate = function (renderId) {
  13685. this._renderId = renderId;
  13686. };
  13687. /**
  13688. * Returns the latest update of the World matrix
  13689. * Returns a Matrix.
  13690. */
  13691. AbstractMesh.prototype.getWorldMatrix = function () {
  13692. if (this._masterMesh) {
  13693. return this._masterMesh.getWorldMatrix();
  13694. }
  13695. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13696. this.computeWorldMatrix();
  13697. }
  13698. return this._worldMatrix;
  13699. };
  13700. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  13701. /**
  13702. * Returns directly the latest state of the mesh World matrix.
  13703. * A Matrix is returned.
  13704. */
  13705. get: function () {
  13706. return this._worldMatrix;
  13707. },
  13708. enumerable: true,
  13709. configurable: true
  13710. });
  13711. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  13712. /**
  13713. * Returns the current mesh absolute position.
  13714. * Retuns a Vector3.
  13715. */
  13716. get: function () {
  13717. return this._absolutePosition;
  13718. },
  13719. enumerable: true,
  13720. configurable: true
  13721. });
  13722. /**
  13723. * Prevents the World matrix to be computed any longer.
  13724. * Returns the AbstractMesh.
  13725. */
  13726. AbstractMesh.prototype.freezeWorldMatrix = function () {
  13727. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13728. this.computeWorldMatrix(true);
  13729. this._isWorldMatrixFrozen = true;
  13730. return this;
  13731. };
  13732. /**
  13733. * Allows back the World matrix computation.
  13734. * Returns the AbstractMesh.
  13735. */
  13736. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  13737. this._isWorldMatrixFrozen = false;
  13738. this.computeWorldMatrix(true);
  13739. return this;
  13740. };
  13741. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  13742. /**
  13743. * True if the World matrix has been frozen.
  13744. * Returns a boolean.
  13745. */
  13746. get: function () {
  13747. return this._isWorldMatrixFrozen;
  13748. },
  13749. enumerable: true,
  13750. configurable: true
  13751. });
  13752. /**
  13753. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13754. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13755. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13756. * The passed axis is also normalized.
  13757. * Returns the AbstractMesh.
  13758. */
  13759. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  13760. axis.normalize();
  13761. if (!this.rotationQuaternion) {
  13762. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13763. this.rotation = BABYLON.Vector3.Zero();
  13764. }
  13765. var rotationQuaternion;
  13766. if (!space || space === BABYLON.Space.LOCAL) {
  13767. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13768. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13769. }
  13770. else {
  13771. if (this.parent) {
  13772. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13773. invertParentWorldMatrix.invert();
  13774. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13775. }
  13776. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  13777. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13778. }
  13779. return this;
  13780. };
  13781. /**
  13782. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13783. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13784. * The passed axis is also normalized.
  13785. * Returns the AbstractMesh.
  13786. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13787. */
  13788. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  13789. axis.normalize();
  13790. if (!this.rotationQuaternion) {
  13791. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13792. this.rotation.copyFromFloats(0, 0, 0);
  13793. }
  13794. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  13795. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  13796. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  13797. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  13798. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  13799. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  13800. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  13801. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  13802. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13803. return this;
  13804. };
  13805. /**
  13806. * Translates the mesh along the axis vector for the passed distance in the given space.
  13807. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13808. * Returns the AbstractMesh.
  13809. */
  13810. AbstractMesh.prototype.translate = function (axis, distance, space) {
  13811. var displacementVector = axis.scale(distance);
  13812. if (!space || space === BABYLON.Space.LOCAL) {
  13813. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  13814. this.setPositionWithLocalVector(tempV3);
  13815. }
  13816. else {
  13817. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  13818. }
  13819. return this;
  13820. };
  13821. /**
  13822. * Adds a rotation step to the mesh current rotation.
  13823. * x, y, z are Euler angles expressed in radians.
  13824. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  13825. * This means this rotation is made in the mesh local space only.
  13826. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  13827. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  13828. * ```javascript
  13829. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  13830. * ```
  13831. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  13832. * 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.
  13833. * Returns the AbstractMesh.
  13834. */
  13835. AbstractMesh.prototype.addRotation = function (x, y, z) {
  13836. var rotationQuaternion;
  13837. if (this.rotationQuaternion) {
  13838. rotationQuaternion = this.rotationQuaternion;
  13839. }
  13840. else {
  13841. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  13842. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  13843. }
  13844. var accumulation = BABYLON.Tmp.Quaternion[0];
  13845. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  13846. rotationQuaternion.multiplyInPlace(accumulation);
  13847. if (!this.rotationQuaternion) {
  13848. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  13849. }
  13850. return this;
  13851. };
  13852. /**
  13853. * Retuns the mesh absolute position in the World.
  13854. * Returns a Vector3.
  13855. */
  13856. AbstractMesh.prototype.getAbsolutePosition = function () {
  13857. this.computeWorldMatrix();
  13858. return this._absolutePosition;
  13859. };
  13860. /**
  13861. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13862. * Returns the AbstractMesh.
  13863. */
  13864. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  13865. if (!absolutePosition) {
  13866. return this;
  13867. }
  13868. var absolutePositionX;
  13869. var absolutePositionY;
  13870. var absolutePositionZ;
  13871. if (absolutePosition.x === undefined) {
  13872. if (arguments.length < 3) {
  13873. return this;
  13874. }
  13875. absolutePositionX = arguments[0];
  13876. absolutePositionY = arguments[1];
  13877. absolutePositionZ = arguments[2];
  13878. }
  13879. else {
  13880. absolutePositionX = absolutePosition.x;
  13881. absolutePositionY = absolutePosition.y;
  13882. absolutePositionZ = absolutePosition.z;
  13883. }
  13884. if (this.parent) {
  13885. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13886. invertParentWorldMatrix.invert();
  13887. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13888. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13889. }
  13890. else {
  13891. this.position.x = absolutePositionX;
  13892. this.position.y = absolutePositionY;
  13893. this.position.z = absolutePositionZ;
  13894. }
  13895. return this;
  13896. };
  13897. // ================================== Point of View Movement =================================
  13898. /**
  13899. * Perform relative position change from the point of view of behind the front of the mesh.
  13900. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13901. * Supports definition of mesh facing forward or backward.
  13902. * @param {number} amountRight
  13903. * @param {number} amountUp
  13904. * @param {number} amountForward
  13905. *
  13906. * Returns the AbstractMesh.
  13907. */
  13908. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  13909. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  13910. return this;
  13911. };
  13912. /**
  13913. * Calculate relative position change from the point of view of behind the front of the mesh.
  13914. * This is performed taking into account the meshes current rotation, so you do not have to care.
  13915. * Supports definition of mesh facing forward or backward.
  13916. * @param {number} amountRight
  13917. * @param {number} amountUp
  13918. * @param {number} amountForward
  13919. *
  13920. * Returns a new Vector3.
  13921. */
  13922. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  13923. var rotMatrix = new BABYLON.Matrix();
  13924. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13925. rotQuaternion.toRotationMatrix(rotMatrix);
  13926. var translationDelta = BABYLON.Vector3.Zero();
  13927. var defForwardMult = this.definedFacingForward ? -1 : 1;
  13928. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  13929. return translationDelta;
  13930. };
  13931. // ================================== Point of View Rotation =================================
  13932. /**
  13933. * Perform relative rotation change from the point of view of behind the front of the mesh.
  13934. * Supports definition of mesh facing forward or backward.
  13935. * @param {number} flipBack
  13936. * @param {number} twirlClockwise
  13937. * @param {number} tiltRight
  13938. *
  13939. * Returns the AbstractMesh.
  13940. */
  13941. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13942. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  13943. return this;
  13944. };
  13945. /**
  13946. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  13947. * Supports definition of mesh facing forward or backward.
  13948. * @param {number} flipBack
  13949. * @param {number} twirlClockwise
  13950. * @param {number} tiltRight
  13951. *
  13952. * Returns a new Vector3.
  13953. */
  13954. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  13955. var defForwardMult = this.definedFacingForward ? 1 : -1;
  13956. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  13957. };
  13958. /**
  13959. * Sets a new pivot matrix to the mesh.
  13960. * Returns the AbstractMesh.
  13961. */
  13962. AbstractMesh.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13963. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13964. this._pivotMatrix = matrix.clone();
  13965. this._cache.pivotMatrixUpdated = true;
  13966. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13967. if (this._postMultiplyPivotMatrix) {
  13968. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13969. }
  13970. return this;
  13971. };
  13972. /**
  13973. * Returns the mesh pivot matrix.
  13974. * Default : Identity.
  13975. * A Matrix is returned.
  13976. */
  13977. AbstractMesh.prototype.getPivotMatrix = function () {
  13978. return this._pivotMatrix;
  13979. };
  13980. AbstractMesh.prototype._isSynchronized = function () {
  13981. if (this._isDirty) {
  13982. return false;
  13983. }
  13984. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  13985. return false;
  13986. if (this._cache.pivotMatrixUpdated) {
  13987. return false;
  13988. }
  13989. if (this.infiniteDistance) {
  13990. return false;
  13991. }
  13992. if (!this._cache.position.equals(this.position))
  13993. return false;
  13994. if (this.rotationQuaternion) {
  13995. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13996. return false;
  13997. }
  13998. if (!this._cache.rotation.equals(this.rotation))
  13999. return false;
  14000. if (!this._cache.scaling.equals(this.scaling))
  14001. return false;
  14002. return true;
  14003. };
  14004. AbstractMesh.prototype._initCache = function () {
  14005. _super.prototype._initCache.call(this);
  14006. this._cache.localMatrixUpdated = false;
  14007. this._cache.position = BABYLON.Vector3.Zero();
  14008. this._cache.scaling = BABYLON.Vector3.Zero();
  14009. this._cache.rotation = BABYLON.Vector3.Zero();
  14010. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14011. this._cache.billboardMode = -1;
  14012. };
  14013. AbstractMesh.prototype.markAsDirty = function (property) {
  14014. if (property === "rotation") {
  14015. this.rotationQuaternion = null;
  14016. }
  14017. this._currentRenderId = Number.MAX_VALUE;
  14018. this._isDirty = true;
  14019. return this;
  14020. };
  14021. /**
  14022. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  14023. */
  14024. AbstractMesh.prototype.getHierarchyBoundingVectors = function () {
  14025. this.computeWorldMatrix(true);
  14026. var min;
  14027. var max;
  14028. var boundingInfo = this.getBoundingInfo();
  14029. if (!this.subMeshes || !boundingInfo) {
  14030. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14031. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  14032. }
  14033. else {
  14034. min = boundingInfo.boundingBox.minimumWorld;
  14035. max = boundingInfo.boundingBox.maximumWorld;
  14036. }
  14037. var descendants = this.getDescendants(false);
  14038. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  14039. var descendant = descendants_1[_i];
  14040. var childMesh = descendant;
  14041. childMesh.computeWorldMatrix(true);
  14042. var childBoundingInfo = childMesh.getBoundingInfo();
  14043. if (childMesh.getTotalVertices() === 0 || !childBoundingInfo) {
  14044. continue;
  14045. }
  14046. var boundingBox = childBoundingInfo.boundingBox;
  14047. var minBox = boundingBox.minimumWorld;
  14048. var maxBox = boundingBox.maximumWorld;
  14049. BABYLON.Tools.CheckExtends(minBox, min, max);
  14050. BABYLON.Tools.CheckExtends(maxBox, min, max);
  14051. }
  14052. return {
  14053. min: min,
  14054. max: max
  14055. };
  14056. };
  14057. /**
  14058. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  14059. * Returns the AbstractMesh.
  14060. */
  14061. AbstractMesh.prototype._updateBoundingInfo = function () {
  14062. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  14063. this._boundingInfo.update(this.worldMatrixFromCache);
  14064. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14065. return this;
  14066. };
  14067. /**
  14068. * Update a mesh's children BoundingInfo objects only.
  14069. * Returns the AbstractMesh.
  14070. */
  14071. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  14072. if (!this.subMeshes) {
  14073. return this;
  14074. }
  14075. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  14076. var subMesh = this.subMeshes[subIndex];
  14077. if (!subMesh.IsGlobal) {
  14078. subMesh.updateBoundingInfo(matrix);
  14079. }
  14080. }
  14081. return this;
  14082. };
  14083. /**
  14084. * Computes the mesh World matrix and returns it.
  14085. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14086. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14087. * If the parameter `force`is set to `true`, the actual computation is done.
  14088. * Returns the mesh World Matrix.
  14089. */
  14090. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  14091. if (this._isWorldMatrixFrozen) {
  14092. return this._worldMatrix;
  14093. }
  14094. if (!force && this.isSynchronized(true)) {
  14095. return this._worldMatrix;
  14096. }
  14097. this._cache.position.copyFrom(this.position);
  14098. this._cache.scaling.copyFrom(this.scaling);
  14099. this._cache.pivotMatrixUpdated = false;
  14100. this._cache.billboardMode = this.billboardMode;
  14101. this._currentRenderId = this.getScene().getRenderId();
  14102. this._isDirty = false;
  14103. // Scaling
  14104. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14105. // Rotation
  14106. //rotate, if quaternion is set and rotation was used
  14107. if (this.rotationQuaternion) {
  14108. var len = this.rotation.length();
  14109. if (len) {
  14110. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14111. this.rotation.copyFromFloats(0, 0, 0);
  14112. }
  14113. }
  14114. if (this.rotationQuaternion) {
  14115. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14116. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14117. }
  14118. else {
  14119. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14120. this._cache.rotation.copyFrom(this.rotation);
  14121. }
  14122. // Translation
  14123. var camera = this.getScene().activeCamera;
  14124. if (this.infiniteDistance && !this.parent && camera) {
  14125. var cameraWorldMatrix = camera.getWorldMatrix();
  14126. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14127. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14128. }
  14129. else {
  14130. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14131. }
  14132. // Composing transformations
  14133. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14134. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14135. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14136. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14137. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  14138. // Need to decompose each rotation here
  14139. var currentPosition = BABYLON.Tmp.Vector3[3];
  14140. if (this.parent && this.parent.getWorldMatrix) {
  14141. if (this._meshToBoneReferal) {
  14142. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14143. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14144. }
  14145. else {
  14146. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14147. }
  14148. }
  14149. else {
  14150. currentPosition.copyFrom(this.position);
  14151. }
  14152. currentPosition.subtractInPlace(camera.globalPosition);
  14153. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14154. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  14155. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14156. }
  14157. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  14158. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14159. }
  14160. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  14161. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14162. }
  14163. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14164. }
  14165. else {
  14166. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14167. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14168. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14169. }
  14170. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14171. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14172. }
  14173. // Local world
  14174. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14175. // Parent
  14176. if (this.parent && this.parent.getWorldMatrix) {
  14177. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  14178. if (this._meshToBoneReferal) {
  14179. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14180. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14181. }
  14182. else {
  14183. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14184. }
  14185. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14186. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14187. this._worldMatrix.copyFrom(this._localWorld);
  14188. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14189. }
  14190. else {
  14191. if (this._meshToBoneReferal) {
  14192. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14193. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14194. }
  14195. else {
  14196. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14197. }
  14198. }
  14199. this._markSyncedWithParent();
  14200. }
  14201. else {
  14202. this._worldMatrix.copyFrom(this._localWorld);
  14203. }
  14204. // Post multiply inverse of pivotMatrix
  14205. if (this._postMultiplyPivotMatrix) {
  14206. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14207. }
  14208. // Normal matrix
  14209. if (this.scaling.isNonUniform) {
  14210. this.nonUniformScaling = true;
  14211. }
  14212. else if (this.parent && this.parent._nonUniformScaling) {
  14213. this.nonUniformScaling = this.parent._nonUniformScaling;
  14214. }
  14215. else {
  14216. this.nonUniformScaling = false;
  14217. }
  14218. // Bounding info
  14219. this._updateBoundingInfo();
  14220. // Absolute position
  14221. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14222. // Callbacks
  14223. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14224. if (!this._poseMatrix) {
  14225. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14226. }
  14227. return this._worldMatrix;
  14228. };
  14229. /**
  14230. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14231. * @param func: callback function to add
  14232. *
  14233. * Returns the AbstractMesh.
  14234. */
  14235. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14236. this.onAfterWorldMatrixUpdateObservable.add(func);
  14237. return this;
  14238. };
  14239. /**
  14240. * Removes a registered callback function.
  14241. * Returns the AbstractMesh.
  14242. */
  14243. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14244. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14245. return this;
  14246. };
  14247. /**
  14248. * Sets the mesh position in its local space.
  14249. * Returns the AbstractMesh.
  14250. */
  14251. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  14252. this.computeWorldMatrix();
  14253. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14254. return this;
  14255. };
  14256. /**
  14257. * Returns the mesh position in the local space from the current World matrix values.
  14258. * Returns a new Vector3.
  14259. */
  14260. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  14261. this.computeWorldMatrix();
  14262. var invLocalWorldMatrix = this._localWorld.clone();
  14263. invLocalWorldMatrix.invert();
  14264. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14265. };
  14266. /**
  14267. * Translates the mesh along the passed Vector3 in its local space.
  14268. * Returns the AbstractMesh.
  14269. */
  14270. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  14271. this.computeWorldMatrix(true);
  14272. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14273. return this;
  14274. };
  14275. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14276. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  14277. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  14278. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  14279. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  14280. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  14281. /// <returns>Mesh oriented towards targetMesh</returns>
  14282. if (yawCor === void 0) { yawCor = 0; }
  14283. if (pitchCor === void 0) { pitchCor = 0; }
  14284. if (rollCor === void 0) { rollCor = 0; }
  14285. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14286. var dv = AbstractMesh._lookAtVectorCache;
  14287. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14288. targetPoint.subtractToRef(pos, dv);
  14289. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14290. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14291. var pitch = Math.atan2(dv.y, len);
  14292. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  14293. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14294. return this;
  14295. };
  14296. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  14297. this._meshToBoneReferal = affectedMesh;
  14298. this.parent = bone;
  14299. if (bone.getWorldMatrix().determinant() < 0) {
  14300. this.scalingDeterminant *= -1;
  14301. }
  14302. return this;
  14303. };
  14304. AbstractMesh.prototype.detachFromBone = function () {
  14305. if (!this.parent) {
  14306. return this;
  14307. }
  14308. if (this.parent.getWorldMatrix().determinant() < 0) {
  14309. this.scalingDeterminant *= -1;
  14310. }
  14311. this._meshToBoneReferal = null;
  14312. this.parent = null;
  14313. return this;
  14314. };
  14315. /**
  14316. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  14317. * A mesh is in the frustum if its bounding box intersects the frustum.
  14318. * Boolean returned.
  14319. */
  14320. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  14321. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  14322. };
  14323. /**
  14324. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  14325. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  14326. * Boolean returned.
  14327. */
  14328. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14329. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  14330. ;
  14331. };
  14332. /**
  14333. * True if the mesh intersects another mesh or a SolidParticle object.
  14334. * 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)
  14335. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  14336. * Returns a boolean.
  14337. */
  14338. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  14339. if (precise === void 0) { precise = false; }
  14340. if (!this._boundingInfo || !mesh._boundingInfo) {
  14341. return false;
  14342. }
  14343. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  14344. return true;
  14345. }
  14346. if (includeDescendants) {
  14347. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  14348. var child = _a[_i];
  14349. if (child.intersectsMesh(mesh, precise, true)) {
  14350. return true;
  14351. }
  14352. }
  14353. }
  14354. return false;
  14355. };
  14356. /**
  14357. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  14358. * Returns a boolean.
  14359. */
  14360. AbstractMesh.prototype.intersectsPoint = function (point) {
  14361. if (!this._boundingInfo) {
  14362. return false;
  14363. }
  14364. return this._boundingInfo.intersectsPoint(point);
  14365. };
  14366. AbstractMesh.prototype.getPhysicsImpostor = function () {
  14367. return this.physicsImpostor;
  14368. };
  14369. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  14370. if (camera === void 0) { camera = null; }
  14371. if (!camera) {
  14372. camera = this.getScene().activeCamera;
  14373. }
  14374. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  14375. };
  14376. /**
  14377. * Returns the distance from the mesh to the active camera.
  14378. * Returns a float.
  14379. */
  14380. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  14381. if (camera === void 0) { camera = null; }
  14382. if (!camera) {
  14383. camera = this.getScene().activeCamera;
  14384. }
  14385. return this.absolutePosition.subtract(camera.position).length();
  14386. };
  14387. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  14388. if (!this.physicsImpostor) {
  14389. return this;
  14390. }
  14391. this.physicsImpostor.applyImpulse(force, contactPoint);
  14392. return this;
  14393. };
  14394. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  14395. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  14396. return this;
  14397. }
  14398. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  14399. mainPivot: pivot1,
  14400. connectedPivot: pivot2,
  14401. nativeParams: options
  14402. });
  14403. return this;
  14404. };
  14405. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  14406. // Collisions
  14407. /**
  14408. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  14409. * Default `false`.
  14410. */
  14411. get: function () {
  14412. return this._checkCollisions;
  14413. },
  14414. set: function (collisionEnabled) {
  14415. this._checkCollisions = collisionEnabled;
  14416. if (this.getScene().workerCollisions) {
  14417. this.getScene().collisionCoordinator.onMeshUpdated(this);
  14418. }
  14419. },
  14420. enumerable: true,
  14421. configurable: true
  14422. });
  14423. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  14424. var globalPosition = this.getAbsolutePosition();
  14425. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  14426. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  14427. if (!this._collider) {
  14428. this._collider = new BABYLON.Collider();
  14429. }
  14430. this._collider.radius = this.ellipsoid;
  14431. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  14432. return this;
  14433. };
  14434. // Submeshes octree
  14435. /**
  14436. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  14437. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  14438. * Returns an Octree of submeshes.
  14439. */
  14440. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  14441. if (maxCapacity === void 0) { maxCapacity = 64; }
  14442. if (maxDepth === void 0) { maxDepth = 2; }
  14443. if (!this._submeshesOctree) {
  14444. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  14445. }
  14446. this.computeWorldMatrix(true);
  14447. var boundingInfo = this.getBoundingInfo();
  14448. // Update octree
  14449. if (boundingInfo) {
  14450. var bbox = boundingInfo.boundingBox;
  14451. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  14452. }
  14453. return this._submeshesOctree;
  14454. };
  14455. // Collisions
  14456. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  14457. this._generatePointsArray();
  14458. if (!this._positions) {
  14459. return this;
  14460. }
  14461. // Transformation
  14462. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  14463. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  14464. subMesh._lastColliderWorldVertices = [];
  14465. subMesh._trianglePlanes = [];
  14466. var start = subMesh.verticesStart;
  14467. var end = (subMesh.verticesStart + subMesh.verticesCount);
  14468. for (var i = start; i < end; i++) {
  14469. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  14470. }
  14471. }
  14472. // Collide
  14473. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  14474. if (collider.collisionFound) {
  14475. collider.collidedMesh = this;
  14476. }
  14477. return this;
  14478. };
  14479. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  14480. var subMeshes;
  14481. var len;
  14482. // Octrees
  14483. if (this._submeshesOctree && this.useOctreeForCollisions) {
  14484. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  14485. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  14486. len = intersections.length;
  14487. subMeshes = intersections.data;
  14488. }
  14489. else {
  14490. subMeshes = this.subMeshes;
  14491. len = subMeshes.length;
  14492. }
  14493. for (var index = 0; index < len; index++) {
  14494. var subMesh = subMeshes[index];
  14495. // Bounding test
  14496. if (len > 1 && !subMesh._checkCollision(collider))
  14497. continue;
  14498. this._collideForSubMesh(subMesh, transformMatrix, collider);
  14499. }
  14500. return this;
  14501. };
  14502. AbstractMesh.prototype._checkCollision = function (collider) {
  14503. // Bounding box test
  14504. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  14505. return this;
  14506. // Transformation matrix
  14507. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  14508. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  14509. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  14510. return this;
  14511. };
  14512. // Picking
  14513. AbstractMesh.prototype._generatePointsArray = function () {
  14514. return false;
  14515. };
  14516. /**
  14517. * Checks if the passed Ray intersects with the mesh.
  14518. * Returns an object PickingInfo.
  14519. */
  14520. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  14521. var pickingInfo = new BABYLON.PickingInfo();
  14522. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  14523. return pickingInfo;
  14524. }
  14525. if (!this._generatePointsArray()) {
  14526. return pickingInfo;
  14527. }
  14528. var intersectInfo = null;
  14529. // Octrees
  14530. var subMeshes;
  14531. var len;
  14532. if (this._submeshesOctree && this.useOctreeForPicking) {
  14533. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  14534. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  14535. len = intersections.length;
  14536. subMeshes = intersections.data;
  14537. }
  14538. else {
  14539. subMeshes = this.subMeshes;
  14540. len = subMeshes.length;
  14541. }
  14542. for (var index = 0; index < len; index++) {
  14543. var subMesh = subMeshes[index];
  14544. // Bounding test
  14545. if (len > 1 && !subMesh.canIntersects(ray))
  14546. continue;
  14547. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  14548. if (currentIntersectInfo) {
  14549. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  14550. intersectInfo = currentIntersectInfo;
  14551. intersectInfo.subMeshId = index;
  14552. if (fastCheck) {
  14553. break;
  14554. }
  14555. }
  14556. }
  14557. }
  14558. if (intersectInfo) {
  14559. // Get picked point
  14560. var world = this.getWorldMatrix();
  14561. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  14562. var direction = ray.direction.clone();
  14563. direction = direction.scale(intersectInfo.distance);
  14564. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  14565. var pickedPoint = worldOrigin.add(worldDirection);
  14566. // Return result
  14567. pickingInfo.hit = true;
  14568. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  14569. pickingInfo.pickedPoint = pickedPoint;
  14570. pickingInfo.pickedMesh = this;
  14571. pickingInfo.bu = intersectInfo.bu || 0;
  14572. pickingInfo.bv = intersectInfo.bv || 0;
  14573. pickingInfo.faceId = intersectInfo.faceId;
  14574. pickingInfo.subMeshId = intersectInfo.subMeshId;
  14575. return pickingInfo;
  14576. }
  14577. return pickingInfo;
  14578. };
  14579. /**
  14580. * Clones the mesh, used by the class Mesh.
  14581. * Just returns `null` for an AbstractMesh.
  14582. */
  14583. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14584. return null;
  14585. };
  14586. /**
  14587. * Disposes all the mesh submeshes.
  14588. * Returns the AbstractMesh.
  14589. */
  14590. AbstractMesh.prototype.releaseSubMeshes = function () {
  14591. if (this.subMeshes) {
  14592. while (this.subMeshes.length) {
  14593. this.subMeshes[0].dispose();
  14594. }
  14595. }
  14596. else {
  14597. this.subMeshes = new Array();
  14598. }
  14599. return this;
  14600. };
  14601. /**
  14602. * Disposes the AbstractMesh.
  14603. * Some internal references are kept for further use.
  14604. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14605. * Returns nothing.
  14606. */
  14607. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  14608. var _this = this;
  14609. var index;
  14610. // Action manager
  14611. if (this.actionManager) {
  14612. this.actionManager.dispose();
  14613. this.actionManager = null;
  14614. }
  14615. // Skeleton
  14616. this.skeleton = null;
  14617. // Animations
  14618. this.getScene().stopAnimation(this);
  14619. // Physics
  14620. if (this.physicsImpostor) {
  14621. this.physicsImpostor.dispose();
  14622. }
  14623. // Intersections in progress
  14624. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  14625. var other = this._intersectionsInProgress[index];
  14626. var pos = other._intersectionsInProgress.indexOf(this);
  14627. other._intersectionsInProgress.splice(pos, 1);
  14628. }
  14629. this._intersectionsInProgress = [];
  14630. // Lights
  14631. var lights = this.getScene().lights;
  14632. lights.forEach(function (light) {
  14633. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  14634. if (meshIndex !== -1) {
  14635. light.includedOnlyMeshes.splice(meshIndex, 1);
  14636. }
  14637. meshIndex = light.excludedMeshes.indexOf(_this);
  14638. if (meshIndex !== -1) {
  14639. light.excludedMeshes.splice(meshIndex, 1);
  14640. }
  14641. // Shadow generators
  14642. var generator = light.getShadowGenerator();
  14643. if (generator) {
  14644. var shadowMap = generator.getShadowMap();
  14645. if (shadowMap && shadowMap.renderList) {
  14646. meshIndex = shadowMap.renderList.indexOf(_this);
  14647. if (meshIndex !== -1) {
  14648. shadowMap.renderList.splice(meshIndex, 1);
  14649. }
  14650. }
  14651. }
  14652. });
  14653. // Edges
  14654. if (this._edgesRenderer) {
  14655. this._edgesRenderer.dispose();
  14656. this._edgesRenderer = null;
  14657. }
  14658. // SubMeshes
  14659. if (this.getClassName() !== "InstancedMesh") {
  14660. this.releaseSubMeshes();
  14661. }
  14662. // Octree
  14663. var sceneOctree = this.getScene().selectionOctree;
  14664. if (sceneOctree) {
  14665. var index = sceneOctree.dynamicContent.indexOf(this);
  14666. if (index !== -1) {
  14667. sceneOctree.dynamicContent.splice(index, 1);
  14668. }
  14669. }
  14670. // Query
  14671. var engine = this.getScene().getEngine();
  14672. if (this._occlusionQuery) {
  14673. this._isOcclusionQueryInProgress = false;
  14674. engine.deleteQuery(this._occlusionQuery);
  14675. this._occlusionQuery = null;
  14676. }
  14677. // Engine
  14678. engine.wipeCaches();
  14679. // Remove from scene
  14680. this.getScene().removeMesh(this);
  14681. if (!doNotRecurse) {
  14682. // Particles
  14683. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  14684. if (this.getScene().particleSystems[index].emitter === this) {
  14685. this.getScene().particleSystems[index].dispose();
  14686. index--;
  14687. }
  14688. }
  14689. // Children
  14690. var objects = this.getDescendants(true);
  14691. for (index = 0; index < objects.length; index++) {
  14692. objects[index].dispose();
  14693. }
  14694. }
  14695. else {
  14696. var childMeshes = this.getChildMeshes(true);
  14697. for (index = 0; index < childMeshes.length; index++) {
  14698. var child = childMeshes[index];
  14699. child.parent = null;
  14700. child.computeWorldMatrix(true);
  14701. }
  14702. }
  14703. // facet data
  14704. if (this._facetDataEnabled) {
  14705. this.disableFacetData();
  14706. }
  14707. this.onAfterWorldMatrixUpdateObservable.clear();
  14708. this.onCollideObservable.clear();
  14709. this.onCollisionPositionChangeObservable.clear();
  14710. this._isDisposed = true;
  14711. _super.prototype.dispose.call(this);
  14712. };
  14713. /**
  14714. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14715. * This Vector3 is expressed in the World space.
  14716. */
  14717. AbstractMesh.prototype.getDirection = function (localAxis) {
  14718. var result = BABYLON.Vector3.Zero();
  14719. this.getDirectionToRef(localAxis, result);
  14720. return result;
  14721. };
  14722. /**
  14723. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14724. * localAxis is expressed in the mesh local space.
  14725. * result is computed in the Wordl space from the mesh World matrix.
  14726. * Returns the AbstractMesh.
  14727. */
  14728. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  14729. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14730. return this;
  14731. };
  14732. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  14733. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14734. if (this.getScene().getRenderId() == 0) {
  14735. this.computeWorldMatrix(true);
  14736. }
  14737. var wm = this.getWorldMatrix();
  14738. if (space == BABYLON.Space.WORLD) {
  14739. var tmat = BABYLON.Tmp.Matrix[0];
  14740. wm.invertToRef(tmat);
  14741. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14742. }
  14743. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14744. this._pivotMatrix.m[12] = -point.x;
  14745. this._pivotMatrix.m[13] = -point.y;
  14746. this._pivotMatrix.m[14] = -point.z;
  14747. this._cache.pivotMatrixUpdated = true;
  14748. return this;
  14749. };
  14750. /**
  14751. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14752. */
  14753. AbstractMesh.prototype.getPivotPoint = function () {
  14754. var point = BABYLON.Vector3.Zero();
  14755. this.getPivotPointToRef(point);
  14756. return point;
  14757. };
  14758. /**
  14759. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14760. * Returns the AbstractMesh.
  14761. */
  14762. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  14763. result.x = -this._pivotMatrix.m[12];
  14764. result.y = -this._pivotMatrix.m[13];
  14765. result.z = -this._pivotMatrix.m[14];
  14766. return this;
  14767. };
  14768. /**
  14769. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14770. */
  14771. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  14772. var point = BABYLON.Vector3.Zero();
  14773. this.getAbsolutePivotPointToRef(point);
  14774. return point;
  14775. };
  14776. /**
  14777. * Defines the passed mesh as the parent of the current mesh.
  14778. * Returns the AbstractMesh.
  14779. */
  14780. AbstractMesh.prototype.setParent = function (mesh) {
  14781. var parent = mesh;
  14782. if (mesh == null) {
  14783. var rotation = BABYLON.Tmp.Quaternion[0];
  14784. var position = BABYLON.Tmp.Vector3[0];
  14785. var scale = BABYLON.Tmp.Vector3[1];
  14786. this.getWorldMatrix().decompose(scale, rotation, position);
  14787. if (this.rotationQuaternion) {
  14788. this.rotationQuaternion.copyFrom(rotation);
  14789. }
  14790. else {
  14791. rotation.toEulerAnglesToRef(this.rotation);
  14792. }
  14793. this.position.x = position.x;
  14794. this.position.y = position.y;
  14795. this.position.z = position.z;
  14796. }
  14797. else {
  14798. var position = BABYLON.Tmp.Vector3[0];
  14799. var m1 = BABYLON.Tmp.Matrix[0];
  14800. parent.getWorldMatrix().invertToRef(m1);
  14801. BABYLON.Vector3.TransformCoordinatesToRef(this.position, m1, position);
  14802. this.position.copyFrom(position);
  14803. }
  14804. this.parent = parent;
  14805. return this;
  14806. };
  14807. /**
  14808. * Adds the passed mesh as a child to the current mesh.
  14809. * Returns the AbstractMesh.
  14810. */
  14811. AbstractMesh.prototype.addChild = function (mesh) {
  14812. mesh.setParent(this);
  14813. return this;
  14814. };
  14815. /**
  14816. * Removes the passed mesh from the current mesh children list.
  14817. * Returns the AbstractMesh.
  14818. */
  14819. AbstractMesh.prototype.removeChild = function (mesh) {
  14820. mesh.setParent(null);
  14821. return this;
  14822. };
  14823. /**
  14824. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14825. * Returns the AbstractMesh.
  14826. */
  14827. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  14828. result.x = this._pivotMatrix.m[12];
  14829. result.y = this._pivotMatrix.m[13];
  14830. result.z = this._pivotMatrix.m[14];
  14831. this.getPivotPointToRef(result);
  14832. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14833. return this;
  14834. };
  14835. // Facet data
  14836. /**
  14837. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  14838. * Returns the AbstractMesh.
  14839. */
  14840. AbstractMesh.prototype._initFacetData = function () {
  14841. if (!this._facetNormals) {
  14842. this._facetNormals = new Array();
  14843. }
  14844. if (!this._facetPositions) {
  14845. this._facetPositions = new Array();
  14846. }
  14847. if (!this._facetPartitioning) {
  14848. this._facetPartitioning = new Array();
  14849. }
  14850. this._facetNb = this.getIndices().length / 3;
  14851. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  14852. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  14853. for (var f = 0; f < this._facetNb; f++) {
  14854. this._facetNormals[f] = BABYLON.Vector3.Zero();
  14855. this._facetPositions[f] = BABYLON.Vector3.Zero();
  14856. }
  14857. this._facetDataEnabled = true;
  14858. return this;
  14859. };
  14860. /**
  14861. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  14862. * This method can be called within the render loop.
  14863. * 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.
  14864. * Returns the AbstractMesh.
  14865. */
  14866. AbstractMesh.prototype.updateFacetData = function () {
  14867. if (!this._facetDataEnabled) {
  14868. this._initFacetData();
  14869. }
  14870. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14871. var indices = this.getIndices();
  14872. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14873. var bInfo = this.getBoundingInfo();
  14874. if (!bInfo) {
  14875. return this;
  14876. }
  14877. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  14878. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  14879. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  14880. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  14881. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  14882. this._subDiv.max = this._partitioningSubdivisions;
  14883. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  14884. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  14885. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  14886. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  14887. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  14888. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  14889. // set the parameters for ComputeNormals()
  14890. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  14891. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  14892. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  14893. this._facetParameters.bInfo = bInfo;
  14894. this._facetParameters.bbSize = this._bbSize;
  14895. this._facetParameters.subDiv = this._subDiv;
  14896. this._facetParameters.ratio = this.partitioningBBoxRatio;
  14897. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  14898. return this;
  14899. };
  14900. /**
  14901. * Returns the facetLocalNormals array.
  14902. * The normals are expressed in the mesh local space.
  14903. */
  14904. AbstractMesh.prototype.getFacetLocalNormals = function () {
  14905. if (!this._facetNormals) {
  14906. this.updateFacetData();
  14907. }
  14908. return this._facetNormals;
  14909. };
  14910. /**
  14911. * Returns the facetLocalPositions array.
  14912. * The facet positions are expressed in the mesh local space.
  14913. */
  14914. AbstractMesh.prototype.getFacetLocalPositions = function () {
  14915. if (!this._facetPositions) {
  14916. this.updateFacetData();
  14917. }
  14918. return this._facetPositions;
  14919. };
  14920. /**
  14921. * Returns the facetLocalPartioning array.
  14922. */
  14923. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  14924. if (!this._facetPartitioning) {
  14925. this.updateFacetData();
  14926. }
  14927. return this._facetPartitioning;
  14928. };
  14929. /**
  14930. * Returns the i-th facet position in the world system.
  14931. * This method allocates a new Vector3 per call.
  14932. */
  14933. AbstractMesh.prototype.getFacetPosition = function (i) {
  14934. var pos = BABYLON.Vector3.Zero();
  14935. this.getFacetPositionToRef(i, pos);
  14936. return pos;
  14937. };
  14938. /**
  14939. * Sets the reference Vector3 with the i-th facet position in the world system.
  14940. * Returns the AbstractMesh.
  14941. */
  14942. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  14943. var localPos = (this.getFacetLocalPositions())[i];
  14944. var world = this.getWorldMatrix();
  14945. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  14946. return this;
  14947. };
  14948. /**
  14949. * Returns the i-th facet normal in the world system.
  14950. * This method allocates a new Vector3 per call.
  14951. */
  14952. AbstractMesh.prototype.getFacetNormal = function (i) {
  14953. var norm = BABYLON.Vector3.Zero();
  14954. this.getFacetNormalToRef(i, norm);
  14955. return norm;
  14956. };
  14957. /**
  14958. * Sets the reference Vector3 with the i-th facet normal in the world system.
  14959. * Returns the AbstractMesh.
  14960. */
  14961. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  14962. var localNorm = (this.getFacetLocalNormals())[i];
  14963. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  14964. return this;
  14965. };
  14966. /**
  14967. * 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).
  14968. */
  14969. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  14970. var bInfo = this.getBoundingInfo();
  14971. if (!bInfo) {
  14972. return null;
  14973. }
  14974. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  14975. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  14976. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  14977. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  14978. return null;
  14979. }
  14980. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  14981. };
  14982. /**
  14983. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  14984. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  14985. * 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.
  14986. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  14987. * 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.
  14988. */
  14989. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  14990. if (checkFace === void 0) { checkFace = false; }
  14991. if (facing === void 0) { facing = true; }
  14992. var world = this.getWorldMatrix();
  14993. var invMat = BABYLON.Tmp.Matrix[5];
  14994. world.invertToRef(invMat);
  14995. var invVect = BABYLON.Tmp.Vector3[8];
  14996. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  14997. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  14998. if (projected) {
  14999. // tranform the local computed projected vector to world coordinates
  15000. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15001. }
  15002. return closest;
  15003. };
  15004. /**
  15005. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15006. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15007. * 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.
  15008. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15009. * 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.
  15010. */
  15011. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15012. if (checkFace === void 0) { checkFace = false; }
  15013. if (facing === void 0) { facing = true; }
  15014. var closest = null;
  15015. var tmpx = 0.0;
  15016. var tmpy = 0.0;
  15017. var tmpz = 0.0;
  15018. var d = 0.0; // tmp dot facet normal * facet position
  15019. var t0 = 0.0;
  15020. var projx = 0.0;
  15021. var projy = 0.0;
  15022. var projz = 0.0;
  15023. // Get all the facets in the same partitioning block than (x, y, z)
  15024. var facetPositions = this.getFacetLocalPositions();
  15025. var facetNormals = this.getFacetLocalNormals();
  15026. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15027. if (!facetsInBlock) {
  15028. return null;
  15029. }
  15030. // Get the closest facet to (x, y, z)
  15031. var shortest = Number.MAX_VALUE; // init distance vars
  15032. var tmpDistance = shortest;
  15033. var fib; // current facet in the block
  15034. var norm; // current facet normal
  15035. var p0; // current facet barycenter position
  15036. // loop on all the facets in the current partitioning block
  15037. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15038. fib = facetsInBlock[idx];
  15039. norm = facetNormals[fib];
  15040. p0 = facetPositions[fib];
  15041. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15042. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15043. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15044. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15045. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15046. projx = x + norm.x * t0;
  15047. projy = y + norm.y * t0;
  15048. projz = z + norm.z * t0;
  15049. tmpx = projx - x;
  15050. tmpy = projy - y;
  15051. tmpz = projz - z;
  15052. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15053. if (tmpDistance < shortest) {
  15054. shortest = tmpDistance;
  15055. closest = fib;
  15056. if (projected) {
  15057. projected.x = projx;
  15058. projected.y = projy;
  15059. projected.z = projz;
  15060. }
  15061. }
  15062. }
  15063. }
  15064. return closest;
  15065. };
  15066. /**
  15067. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15068. */
  15069. AbstractMesh.prototype.getFacetDataParameters = function () {
  15070. return this._facetParameters;
  15071. };
  15072. /**
  15073. * Disables the feature FacetData and frees the related memory.
  15074. * Returns the AbstractMesh.
  15075. */
  15076. AbstractMesh.prototype.disableFacetData = function () {
  15077. if (this._facetDataEnabled) {
  15078. this._facetDataEnabled = false;
  15079. this._facetPositions = new Array();
  15080. ;
  15081. this._facetNormals = new Array();
  15082. ;
  15083. this._facetPartitioning = new Array();
  15084. ;
  15085. this._facetParameters = null;
  15086. }
  15087. return this;
  15088. };
  15089. /**
  15090. * Creates new normals data for the mesh.
  15091. * @param updatable.
  15092. */
  15093. AbstractMesh.prototype.createNormals = function (updatable) {
  15094. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15095. var indices = this.getIndices();
  15096. var normals;
  15097. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15098. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15099. }
  15100. else {
  15101. normals = [];
  15102. }
  15103. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  15104. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  15105. };
  15106. AbstractMesh.prototype.checkOcclusionQuery = function () {
  15107. var engine = this.getEngine();
  15108. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  15109. this._isOccluded = false;
  15110. return;
  15111. }
  15112. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  15113. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  15114. if (isOcclusionQueryAvailable) {
  15115. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  15116. this._isOcclusionQueryInProgress = false;
  15117. this._occlusionInternalRetryCounter = 0;
  15118. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  15119. }
  15120. else {
  15121. this._occlusionInternalRetryCounter++;
  15122. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  15123. this._isOcclusionQueryInProgress = false;
  15124. this._occlusionInternalRetryCounter = 0;
  15125. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  15126. // if strict continue the last state of the object.
  15127. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  15128. }
  15129. else {
  15130. return;
  15131. }
  15132. }
  15133. }
  15134. var scene = this.getScene();
  15135. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  15136. if (!this._occlusionQuery) {
  15137. this._occlusionQuery = engine.createQuery();
  15138. }
  15139. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  15140. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  15141. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  15142. this._isOcclusionQueryInProgress = true;
  15143. };
  15144. // Statics
  15145. AbstractMesh._BILLBOARDMODE_NONE = 0;
  15146. AbstractMesh._BILLBOARDMODE_X = 1;
  15147. AbstractMesh._BILLBOARDMODE_Y = 2;
  15148. AbstractMesh._BILLBOARDMODE_Z = 4;
  15149. AbstractMesh._BILLBOARDMODE_ALL = 7;
  15150. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  15151. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  15152. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  15153. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  15154. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  15155. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  15156. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15157. return AbstractMesh;
  15158. }(BABYLON.Node));
  15159. BABYLON.AbstractMesh = AbstractMesh;
  15160. })(BABYLON || (BABYLON = {}));
  15161. //# sourceMappingURL=babylon.abstractMesh.js.map
  15162. var BABYLON;
  15163. (function (BABYLON) {
  15164. var Light = /** @class */ (function (_super) {
  15165. __extends(Light, _super);
  15166. /**
  15167. * Creates a Light object in the scene.
  15168. * Documentation : http://doc.babylonjs.com/tutorials/lights
  15169. */
  15170. function Light(name, scene) {
  15171. var _this = _super.call(this, name, scene) || this;
  15172. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  15173. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  15174. _this.intensity = 1.0;
  15175. _this.range = Number.MAX_VALUE;
  15176. /**
  15177. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  15178. * of light.
  15179. */
  15180. _this._photometricScale = 1.0;
  15181. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  15182. _this._radius = 0.00001;
  15183. _this.renderPriority = 0;
  15184. /**
  15185. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  15186. * the current shadow generator.
  15187. */
  15188. _this.shadowEnabled = true;
  15189. _this._excludeWithLayerMask = 0;
  15190. _this._includeOnlyWithLayerMask = 0;
  15191. _this._lightmapMode = 0;
  15192. _this._excludedMeshesIds = new Array();
  15193. _this._includedOnlyMeshesIds = new Array();
  15194. _this.getScene().addLight(_this);
  15195. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  15196. _this._buildUniformLayout();
  15197. _this.includedOnlyMeshes = new Array();
  15198. _this.excludedMeshes = new Array();
  15199. _this._resyncMeshes();
  15200. return _this;
  15201. }
  15202. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  15203. /**
  15204. * If every light affecting the material is in this lightmapMode,
  15205. * material.lightmapTexture adds or multiplies
  15206. * (depends on material.useLightmapAsShadowmap)
  15207. * after every other light calculations.
  15208. */
  15209. get: function () {
  15210. return Light._LIGHTMAP_DEFAULT;
  15211. },
  15212. enumerable: true,
  15213. configurable: true
  15214. });
  15215. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  15216. /**
  15217. * material.lightmapTexture as only diffuse lighting from this light
  15218. * adds pnly specular lighting from this light
  15219. * adds dynamic shadows
  15220. */
  15221. get: function () {
  15222. return Light._LIGHTMAP_SPECULAR;
  15223. },
  15224. enumerable: true,
  15225. configurable: true
  15226. });
  15227. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  15228. /**
  15229. * material.lightmapTexture as only lighting
  15230. * no light calculation from this light
  15231. * only adds dynamic shadows from this light
  15232. */
  15233. get: function () {
  15234. return Light._LIGHTMAP_SHADOWSONLY;
  15235. },
  15236. enumerable: true,
  15237. configurable: true
  15238. });
  15239. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  15240. /**
  15241. * Each light type uses the default quantity according to its type:
  15242. * point/spot lights use luminous intensity
  15243. * directional lights use illuminance
  15244. */
  15245. get: function () {
  15246. return Light._INTENSITYMODE_AUTOMATIC;
  15247. },
  15248. enumerable: true,
  15249. configurable: true
  15250. });
  15251. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  15252. /**
  15253. * lumen (lm)
  15254. */
  15255. get: function () {
  15256. return Light._INTENSITYMODE_LUMINOUSPOWER;
  15257. },
  15258. enumerable: true,
  15259. configurable: true
  15260. });
  15261. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  15262. /**
  15263. * candela (lm/sr)
  15264. */
  15265. get: function () {
  15266. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  15267. },
  15268. enumerable: true,
  15269. configurable: true
  15270. });
  15271. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  15272. /**
  15273. * lux (lm/m^2)
  15274. */
  15275. get: function () {
  15276. return Light._INTENSITYMODE_ILLUMINANCE;
  15277. },
  15278. enumerable: true,
  15279. configurable: true
  15280. });
  15281. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  15282. /**
  15283. * nit (cd/m^2)
  15284. */
  15285. get: function () {
  15286. return Light._INTENSITYMODE_LUMINANCE;
  15287. },
  15288. enumerable: true,
  15289. configurable: true
  15290. });
  15291. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  15292. /**
  15293. * Light type const id of the point light.
  15294. */
  15295. get: function () {
  15296. return Light._LIGHTTYPEID_POINTLIGHT;
  15297. },
  15298. enumerable: true,
  15299. configurable: true
  15300. });
  15301. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  15302. /**
  15303. * Light type const id of the directional light.
  15304. */
  15305. get: function () {
  15306. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  15307. },
  15308. enumerable: true,
  15309. configurable: true
  15310. });
  15311. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  15312. /**
  15313. * Light type const id of the spot light.
  15314. */
  15315. get: function () {
  15316. return Light._LIGHTTYPEID_SPOTLIGHT;
  15317. },
  15318. enumerable: true,
  15319. configurable: true
  15320. });
  15321. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  15322. /**
  15323. * Light type const id of the hemispheric light.
  15324. */
  15325. get: function () {
  15326. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  15327. },
  15328. enumerable: true,
  15329. configurable: true
  15330. });
  15331. Object.defineProperty(Light.prototype, "intensityMode", {
  15332. /**
  15333. * Gets the photometric scale used to interpret the intensity.
  15334. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15335. */
  15336. get: function () {
  15337. return this._intensityMode;
  15338. },
  15339. /**
  15340. * Sets the photometric scale used to interpret the intensity.
  15341. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  15342. */
  15343. set: function (value) {
  15344. this._intensityMode = value;
  15345. this._computePhotometricScale();
  15346. },
  15347. enumerable: true,
  15348. configurable: true
  15349. });
  15350. ;
  15351. ;
  15352. Object.defineProperty(Light.prototype, "radius", {
  15353. /**
  15354. * Gets the light radius used by PBR Materials to simulate soft area lights.
  15355. */
  15356. get: function () {
  15357. return this._radius;
  15358. },
  15359. /**
  15360. * sets the light radius used by PBR Materials to simulate soft area lights.
  15361. */
  15362. set: function (value) {
  15363. this._radius = value;
  15364. this._computePhotometricScale();
  15365. },
  15366. enumerable: true,
  15367. configurable: true
  15368. });
  15369. ;
  15370. ;
  15371. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  15372. get: function () {
  15373. return this._includedOnlyMeshes;
  15374. },
  15375. set: function (value) {
  15376. this._includedOnlyMeshes = value;
  15377. this._hookArrayForIncludedOnly(value);
  15378. },
  15379. enumerable: true,
  15380. configurable: true
  15381. });
  15382. Object.defineProperty(Light.prototype, "excludedMeshes", {
  15383. get: function () {
  15384. return this._excludedMeshes;
  15385. },
  15386. set: function (value) {
  15387. this._excludedMeshes = value;
  15388. this._hookArrayForExcluded(value);
  15389. },
  15390. enumerable: true,
  15391. configurable: true
  15392. });
  15393. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  15394. get: function () {
  15395. return this._excludeWithLayerMask;
  15396. },
  15397. set: function (value) {
  15398. this._excludeWithLayerMask = value;
  15399. this._resyncMeshes();
  15400. },
  15401. enumerable: true,
  15402. configurable: true
  15403. });
  15404. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  15405. get: function () {
  15406. return this._includeOnlyWithLayerMask;
  15407. },
  15408. set: function (value) {
  15409. this._includeOnlyWithLayerMask = value;
  15410. this._resyncMeshes();
  15411. },
  15412. enumerable: true,
  15413. configurable: true
  15414. });
  15415. Object.defineProperty(Light.prototype, "lightmapMode", {
  15416. get: function () {
  15417. return this._lightmapMode;
  15418. },
  15419. set: function (value) {
  15420. if (this._lightmapMode === value) {
  15421. return;
  15422. }
  15423. this._lightmapMode = value;
  15424. this._markMeshesAsLightDirty();
  15425. },
  15426. enumerable: true,
  15427. configurable: true
  15428. });
  15429. Light.prototype._buildUniformLayout = function () {
  15430. // Overridden
  15431. };
  15432. /**
  15433. * Returns the string "Light".
  15434. */
  15435. Light.prototype.getClassName = function () {
  15436. return "Light";
  15437. };
  15438. /**
  15439. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15440. */
  15441. Light.prototype.toString = function (fullDetails) {
  15442. var ret = "Name: " + this.name;
  15443. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  15444. if (this.animations) {
  15445. for (var i = 0; i < this.animations.length; i++) {
  15446. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  15447. }
  15448. }
  15449. if (fullDetails) {
  15450. }
  15451. return ret;
  15452. };
  15453. /**
  15454. * Set the enabled state of this node.
  15455. * @param {boolean} value - the new enabled state
  15456. * @see isEnabled
  15457. */
  15458. Light.prototype.setEnabled = function (value) {
  15459. _super.prototype.setEnabled.call(this, value);
  15460. this._resyncMeshes();
  15461. };
  15462. /**
  15463. * Returns the Light associated shadow generator.
  15464. */
  15465. Light.prototype.getShadowGenerator = function () {
  15466. return this._shadowGenerator;
  15467. };
  15468. /**
  15469. * Returns a Vector3, the absolute light position in the World.
  15470. */
  15471. Light.prototype.getAbsolutePosition = function () {
  15472. return BABYLON.Vector3.Zero();
  15473. };
  15474. Light.prototype.transferToEffect = function (effect, lightIndex) {
  15475. };
  15476. Light.prototype._getWorldMatrix = function () {
  15477. return BABYLON.Matrix.Identity();
  15478. };
  15479. /**
  15480. * Boolean : True if the light will affect the passed mesh.
  15481. */
  15482. Light.prototype.canAffectMesh = function (mesh) {
  15483. if (!mesh) {
  15484. return true;
  15485. }
  15486. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  15487. return false;
  15488. }
  15489. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  15490. return false;
  15491. }
  15492. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  15493. return false;
  15494. }
  15495. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  15496. return false;
  15497. }
  15498. return true;
  15499. };
  15500. /**
  15501. * Returns the light World matrix.
  15502. */
  15503. Light.prototype.getWorldMatrix = function () {
  15504. this._currentRenderId = this.getScene().getRenderId();
  15505. var worldMatrix = this._getWorldMatrix();
  15506. if (this.parent && this.parent.getWorldMatrix) {
  15507. if (!this._parentedWorldMatrix) {
  15508. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  15509. }
  15510. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  15511. this._markSyncedWithParent();
  15512. return this._parentedWorldMatrix;
  15513. }
  15514. return worldMatrix;
  15515. };
  15516. /**
  15517. * Sort function to order lights for rendering.
  15518. * @param a First Light object to compare to second.
  15519. * @param b Second Light object to compare first.
  15520. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  15521. */
  15522. Light.compareLightsPriority = function (a, b) {
  15523. //shadow-casting lights have priority over non-shadow-casting lights
  15524. //the renderPrioirty is a secondary sort criterion
  15525. if (a.shadowEnabled !== b.shadowEnabled) {
  15526. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  15527. }
  15528. return b.renderPriority - a.renderPriority;
  15529. };
  15530. /**
  15531. * Disposes the light.
  15532. */
  15533. Light.prototype.dispose = function () {
  15534. if (this._shadowGenerator) {
  15535. this._shadowGenerator.dispose();
  15536. this._shadowGenerator = null;
  15537. }
  15538. // Animations
  15539. this.getScene().stopAnimation(this);
  15540. // Remove from meshes
  15541. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15542. var mesh = _a[_i];
  15543. mesh._removeLightSource(this);
  15544. }
  15545. this._uniformBuffer.dispose();
  15546. // Remove from scene
  15547. this.getScene().removeLight(this);
  15548. _super.prototype.dispose.call(this);
  15549. };
  15550. /**
  15551. * Returns the light type ID (integer).
  15552. */
  15553. Light.prototype.getTypeID = function () {
  15554. return 0;
  15555. };
  15556. /**
  15557. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  15558. */
  15559. Light.prototype.getScaledIntensity = function () {
  15560. return this._photometricScale * this.intensity;
  15561. };
  15562. /**
  15563. * Returns a new Light object, named "name", from the current one.
  15564. */
  15565. Light.prototype.clone = function (name) {
  15566. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  15567. if (!constructor) {
  15568. return null;
  15569. }
  15570. return BABYLON.SerializationHelper.Clone(constructor, this);
  15571. };
  15572. /**
  15573. * Serializes the current light into a Serialization object.
  15574. * Returns the serialized object.
  15575. */
  15576. Light.prototype.serialize = function () {
  15577. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15578. // Type
  15579. serializationObject.type = this.getTypeID();
  15580. // Parent
  15581. if (this.parent) {
  15582. serializationObject.parentId = this.parent.id;
  15583. }
  15584. // Inclusion / exclusions
  15585. if (this.excludedMeshes.length > 0) {
  15586. serializationObject.excludedMeshesIds = [];
  15587. this.excludedMeshes.forEach(function (mesh) {
  15588. serializationObject.excludedMeshesIds.push(mesh.id);
  15589. });
  15590. }
  15591. if (this.includedOnlyMeshes.length > 0) {
  15592. serializationObject.includedOnlyMeshesIds = [];
  15593. this.includedOnlyMeshes.forEach(function (mesh) {
  15594. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  15595. });
  15596. }
  15597. // Animations
  15598. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15599. serializationObject.ranges = this.serializeAnimationRanges();
  15600. return serializationObject;
  15601. };
  15602. /**
  15603. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  15604. * This new light is named "name" and added to the passed scene.
  15605. */
  15606. Light.GetConstructorFromName = function (type, name, scene) {
  15607. switch (type) {
  15608. case 0:
  15609. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  15610. case 1:
  15611. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  15612. case 2:
  15613. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  15614. case 3:
  15615. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  15616. }
  15617. return null;
  15618. };
  15619. /**
  15620. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  15621. */
  15622. Light.Parse = function (parsedLight, scene) {
  15623. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  15624. if (!constructor) {
  15625. return null;
  15626. }
  15627. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  15628. // Inclusion / exclusions
  15629. if (parsedLight.excludedMeshesIds) {
  15630. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  15631. }
  15632. if (parsedLight.includedOnlyMeshesIds) {
  15633. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  15634. }
  15635. // Parent
  15636. if (parsedLight.parentId) {
  15637. light._waitingParentId = parsedLight.parentId;
  15638. }
  15639. // Animations
  15640. if (parsedLight.animations) {
  15641. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  15642. var parsedAnimation = parsedLight.animations[animationIndex];
  15643. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15644. }
  15645. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  15646. }
  15647. if (parsedLight.autoAnimate) {
  15648. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  15649. }
  15650. return light;
  15651. };
  15652. Light.prototype._hookArrayForExcluded = function (array) {
  15653. var _this = this;
  15654. var oldPush = array.push;
  15655. array.push = function () {
  15656. var items = [];
  15657. for (var _i = 0; _i < arguments.length; _i++) {
  15658. items[_i] = arguments[_i];
  15659. }
  15660. var result = oldPush.apply(array, items);
  15661. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  15662. var item = items_1[_a];
  15663. item._resyncLighSource(_this);
  15664. }
  15665. return result;
  15666. };
  15667. var oldSplice = array.splice;
  15668. array.splice = function (index, deleteCount) {
  15669. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15670. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  15671. var item = deleted_1[_i];
  15672. item._resyncLighSource(_this);
  15673. }
  15674. return deleted;
  15675. };
  15676. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  15677. var item = array_1[_i];
  15678. item._resyncLighSource(this);
  15679. }
  15680. };
  15681. Light.prototype._hookArrayForIncludedOnly = function (array) {
  15682. var _this = this;
  15683. var oldPush = array.push;
  15684. array.push = function () {
  15685. var items = [];
  15686. for (var _i = 0; _i < arguments.length; _i++) {
  15687. items[_i] = arguments[_i];
  15688. }
  15689. var result = oldPush.apply(array, items);
  15690. _this._resyncMeshes();
  15691. return result;
  15692. };
  15693. var oldSplice = array.splice;
  15694. array.splice = function (index, deleteCount) {
  15695. var deleted = oldSplice.apply(array, [index, deleteCount]);
  15696. _this._resyncMeshes();
  15697. return deleted;
  15698. };
  15699. this._resyncMeshes();
  15700. };
  15701. Light.prototype._resyncMeshes = function () {
  15702. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15703. var mesh = _a[_i];
  15704. mesh._resyncLighSource(this);
  15705. }
  15706. };
  15707. Light.prototype._markMeshesAsLightDirty = function () {
  15708. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  15709. var mesh = _a[_i];
  15710. if (mesh._lightSources.indexOf(this) !== -1) {
  15711. mesh._markSubMeshesAsLightDirty();
  15712. }
  15713. }
  15714. };
  15715. /**
  15716. * Recomputes the cached photometric scale if needed.
  15717. */
  15718. Light.prototype._computePhotometricScale = function () {
  15719. this._photometricScale = this._getPhotometricScale();
  15720. this.getScene().resetCachedMaterial();
  15721. };
  15722. /**
  15723. * Returns the Photometric Scale according to the light type and intensity mode.
  15724. */
  15725. Light.prototype._getPhotometricScale = function () {
  15726. var photometricScale = 0.0;
  15727. var lightTypeID = this.getTypeID();
  15728. //get photometric mode
  15729. var photometricMode = this.intensityMode;
  15730. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  15731. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  15732. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  15733. }
  15734. else {
  15735. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  15736. }
  15737. }
  15738. //compute photometric scale
  15739. switch (lightTypeID) {
  15740. case Light.LIGHTTYPEID_POINTLIGHT:
  15741. case Light.LIGHTTYPEID_SPOTLIGHT:
  15742. switch (photometricMode) {
  15743. case Light.INTENSITYMODE_LUMINOUSPOWER:
  15744. photometricScale = 1.0 / (4.0 * Math.PI);
  15745. break;
  15746. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  15747. photometricScale = 1.0;
  15748. break;
  15749. case Light.INTENSITYMODE_LUMINANCE:
  15750. photometricScale = this.radius * this.radius;
  15751. break;
  15752. }
  15753. break;
  15754. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  15755. switch (photometricMode) {
  15756. case Light.INTENSITYMODE_ILLUMINANCE:
  15757. photometricScale = 1.0;
  15758. break;
  15759. case Light.INTENSITYMODE_LUMINANCE:
  15760. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  15761. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  15762. var apexAngleRadians = this.radius;
  15763. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  15764. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  15765. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  15766. photometricScale = solidAngle;
  15767. break;
  15768. }
  15769. break;
  15770. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  15771. // No fall off in hemisperic light.
  15772. photometricScale = 1.0;
  15773. break;
  15774. }
  15775. return photometricScale;
  15776. };
  15777. Light.prototype._reorderLightsInScene = function () {
  15778. var scene = this.getScene();
  15779. if (this._renderPriority != 0) {
  15780. scene.requireLightSorting = true;
  15781. }
  15782. this.getScene().sortLightsByPriority();
  15783. };
  15784. //lightmapMode Consts
  15785. Light._LIGHTMAP_DEFAULT = 0;
  15786. Light._LIGHTMAP_SPECULAR = 1;
  15787. Light._LIGHTMAP_SHADOWSONLY = 2;
  15788. // Intensity Mode Consts
  15789. Light._INTENSITYMODE_AUTOMATIC = 0;
  15790. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  15791. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  15792. Light._INTENSITYMODE_ILLUMINANCE = 3;
  15793. Light._INTENSITYMODE_LUMINANCE = 4;
  15794. // Light types ids const.
  15795. Light._LIGHTTYPEID_POINTLIGHT = 0;
  15796. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  15797. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  15798. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  15799. __decorate([
  15800. BABYLON.serializeAsColor3()
  15801. ], Light.prototype, "diffuse", void 0);
  15802. __decorate([
  15803. BABYLON.serializeAsColor3()
  15804. ], Light.prototype, "specular", void 0);
  15805. __decorate([
  15806. BABYLON.serialize()
  15807. ], Light.prototype, "intensity", void 0);
  15808. __decorate([
  15809. BABYLON.serialize()
  15810. ], Light.prototype, "range", void 0);
  15811. __decorate([
  15812. BABYLON.serialize()
  15813. ], Light.prototype, "intensityMode", null);
  15814. __decorate([
  15815. BABYLON.serialize()
  15816. ], Light.prototype, "radius", null);
  15817. __decorate([
  15818. BABYLON.serialize()
  15819. ], Light.prototype, "_renderPriority", void 0);
  15820. __decorate([
  15821. BABYLON.expandToProperty("_reorderLightsInScene")
  15822. ], Light.prototype, "renderPriority", void 0);
  15823. __decorate([
  15824. BABYLON.serialize()
  15825. ], Light.prototype, "shadowEnabled", void 0);
  15826. __decorate([
  15827. BABYLON.serialize("excludeWithLayerMask")
  15828. ], Light.prototype, "_excludeWithLayerMask", void 0);
  15829. __decorate([
  15830. BABYLON.serialize("includeOnlyWithLayerMask")
  15831. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  15832. __decorate([
  15833. BABYLON.serialize("lightmapMode")
  15834. ], Light.prototype, "_lightmapMode", void 0);
  15835. return Light;
  15836. }(BABYLON.Node));
  15837. BABYLON.Light = Light;
  15838. })(BABYLON || (BABYLON = {}));
  15839. //# sourceMappingURL=babylon.light.js.map
  15840. var BABYLON;
  15841. (function (BABYLON) {
  15842. var Camera = /** @class */ (function (_super) {
  15843. __extends(Camera, _super);
  15844. function Camera(name, position, scene) {
  15845. var _this = _super.call(this, name, scene) || this;
  15846. _this.upVector = BABYLON.Vector3.Up();
  15847. _this.orthoLeft = null;
  15848. _this.orthoRight = null;
  15849. _this.orthoBottom = null;
  15850. _this.orthoTop = null;
  15851. _this.fov = 0.8;
  15852. _this.minZ = 1;
  15853. _this.maxZ = 10000.0;
  15854. _this.inertia = 0.9;
  15855. _this.mode = Camera.PERSPECTIVE_CAMERA;
  15856. _this.isIntermediate = false;
  15857. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  15858. _this.layerMask = 0x0FFFFFFF;
  15859. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  15860. // Camera rig members
  15861. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  15862. _this._rigCameras = new Array();
  15863. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  15864. _this._skipRendering = false;
  15865. _this.customRenderTargets = new Array();
  15866. // Observables
  15867. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  15868. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  15869. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  15870. _this.onRestoreStateObservable = new BABYLON.Observable();
  15871. // Cache
  15872. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  15873. _this._projectionMatrix = new BABYLON.Matrix();
  15874. _this._doNotComputeProjectionMatrix = false;
  15875. _this._postProcesses = new Array();
  15876. _this._transformMatrix = BABYLON.Matrix.Zero();
  15877. _this._activeMeshes = new BABYLON.SmartArray(256);
  15878. _this._globalPosition = BABYLON.Vector3.Zero();
  15879. _this._refreshFrustumPlanes = true;
  15880. _this.getScene().addCamera(_this);
  15881. if (!_this.getScene().activeCamera) {
  15882. _this.getScene().activeCamera = _this;
  15883. }
  15884. _this.position = position;
  15885. return _this;
  15886. }
  15887. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  15888. get: function () {
  15889. return Camera._PERSPECTIVE_CAMERA;
  15890. },
  15891. enumerable: true,
  15892. configurable: true
  15893. });
  15894. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  15895. get: function () {
  15896. return Camera._ORTHOGRAPHIC_CAMERA;
  15897. },
  15898. enumerable: true,
  15899. configurable: true
  15900. });
  15901. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  15902. get: function () {
  15903. return Camera._FOVMODE_VERTICAL_FIXED;
  15904. },
  15905. enumerable: true,
  15906. configurable: true
  15907. });
  15908. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  15909. get: function () {
  15910. return Camera._FOVMODE_HORIZONTAL_FIXED;
  15911. },
  15912. enumerable: true,
  15913. configurable: true
  15914. });
  15915. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  15916. get: function () {
  15917. return Camera._RIG_MODE_NONE;
  15918. },
  15919. enumerable: true,
  15920. configurable: true
  15921. });
  15922. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  15923. get: function () {
  15924. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  15925. },
  15926. enumerable: true,
  15927. configurable: true
  15928. });
  15929. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  15930. get: function () {
  15931. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  15932. },
  15933. enumerable: true,
  15934. configurable: true
  15935. });
  15936. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  15937. get: function () {
  15938. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15939. },
  15940. enumerable: true,
  15941. configurable: true
  15942. });
  15943. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  15944. get: function () {
  15945. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  15946. },
  15947. enumerable: true,
  15948. configurable: true
  15949. });
  15950. Object.defineProperty(Camera, "RIG_MODE_VR", {
  15951. get: function () {
  15952. return Camera._RIG_MODE_VR;
  15953. },
  15954. enumerable: true,
  15955. configurable: true
  15956. });
  15957. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  15958. get: function () {
  15959. return Camera._RIG_MODE_WEBVR;
  15960. },
  15961. enumerable: true,
  15962. configurable: true
  15963. });
  15964. /**
  15965. * Store current camera state (fov, position, etc..)
  15966. */
  15967. Camera.prototype.storeState = function () {
  15968. this._stateStored = true;
  15969. this._storedFov = this.fov;
  15970. return this;
  15971. };
  15972. /**
  15973. * Restores the camera state values if it has been stored. You must call storeState() first
  15974. */
  15975. Camera.prototype._restoreStateValues = function () {
  15976. if (!this._stateStored) {
  15977. return false;
  15978. }
  15979. this.fov = this._storedFov;
  15980. return true;
  15981. };
  15982. /**
  15983. * Restored camera state. You must call storeState() first
  15984. */
  15985. Camera.prototype.restoreState = function () {
  15986. if (this._restoreStateValues()) {
  15987. this.onRestoreStateObservable.notifyObservers(this);
  15988. return true;
  15989. }
  15990. return false;
  15991. };
  15992. Camera.prototype.getClassName = function () {
  15993. return "Camera";
  15994. };
  15995. /**
  15996. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15997. */
  15998. Camera.prototype.toString = function (fullDetails) {
  15999. var ret = "Name: " + this.name;
  16000. ret += ", type: " + this.getClassName();
  16001. if (this.animations) {
  16002. for (var i = 0; i < this.animations.length; i++) {
  16003. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16004. }
  16005. }
  16006. if (fullDetails) {
  16007. }
  16008. return ret;
  16009. };
  16010. Object.defineProperty(Camera.prototype, "globalPosition", {
  16011. get: function () {
  16012. return this._globalPosition;
  16013. },
  16014. enumerable: true,
  16015. configurable: true
  16016. });
  16017. Camera.prototype.getActiveMeshes = function () {
  16018. return this._activeMeshes;
  16019. };
  16020. Camera.prototype.isActiveMesh = function (mesh) {
  16021. return (this._activeMeshes.indexOf(mesh) !== -1);
  16022. };
  16023. //Cache
  16024. Camera.prototype._initCache = function () {
  16025. _super.prototype._initCache.call(this);
  16026. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16027. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16028. this._cache.mode = undefined;
  16029. this._cache.minZ = undefined;
  16030. this._cache.maxZ = undefined;
  16031. this._cache.fov = undefined;
  16032. this._cache.fovMode = undefined;
  16033. this._cache.aspectRatio = undefined;
  16034. this._cache.orthoLeft = undefined;
  16035. this._cache.orthoRight = undefined;
  16036. this._cache.orthoBottom = undefined;
  16037. this._cache.orthoTop = undefined;
  16038. this._cache.renderWidth = undefined;
  16039. this._cache.renderHeight = undefined;
  16040. };
  16041. Camera.prototype._updateCache = function (ignoreParentClass) {
  16042. if (!ignoreParentClass) {
  16043. _super.prototype._updateCache.call(this);
  16044. }
  16045. this._cache.position.copyFrom(this.position);
  16046. this._cache.upVector.copyFrom(this.upVector);
  16047. };
  16048. // Synchronized
  16049. Camera.prototype._isSynchronized = function () {
  16050. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16051. };
  16052. Camera.prototype._isSynchronizedViewMatrix = function () {
  16053. if (!_super.prototype._isSynchronized.call(this))
  16054. return false;
  16055. return this._cache.position.equals(this.position)
  16056. && this._cache.upVector.equals(this.upVector)
  16057. && this.isSynchronizedWithParent();
  16058. };
  16059. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16060. var check = this._cache.mode === this.mode
  16061. && this._cache.minZ === this.minZ
  16062. && this._cache.maxZ === this.maxZ;
  16063. if (!check) {
  16064. return false;
  16065. }
  16066. var engine = this.getEngine();
  16067. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16068. check = this._cache.fov === this.fov
  16069. && this._cache.fovMode === this.fovMode
  16070. && this._cache.aspectRatio === engine.getAspectRatio(this);
  16071. }
  16072. else {
  16073. check = this._cache.orthoLeft === this.orthoLeft
  16074. && this._cache.orthoRight === this.orthoRight
  16075. && this._cache.orthoBottom === this.orthoBottom
  16076. && this._cache.orthoTop === this.orthoTop
  16077. && this._cache.renderWidth === engine.getRenderWidth()
  16078. && this._cache.renderHeight === engine.getRenderHeight();
  16079. }
  16080. return check;
  16081. };
  16082. // Controls
  16083. Camera.prototype.attachControl = function (element, noPreventDefault) {
  16084. };
  16085. Camera.prototype.detachControl = function (element) {
  16086. };
  16087. Camera.prototype.update = function () {
  16088. this._checkInputs();
  16089. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16090. this._updateRigCameras();
  16091. }
  16092. };
  16093. Camera.prototype._checkInputs = function () {
  16094. this.onAfterCheckInputsObservable.notifyObservers(this);
  16095. };
  16096. Object.defineProperty(Camera.prototype, "rigCameras", {
  16097. get: function () {
  16098. return this._rigCameras;
  16099. },
  16100. enumerable: true,
  16101. configurable: true
  16102. });
  16103. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  16104. get: function () {
  16105. return this._rigPostProcess;
  16106. },
  16107. enumerable: true,
  16108. configurable: true
  16109. });
  16110. Camera.prototype._cascadePostProcessesToRigCams = function () {
  16111. // invalidate framebuffer
  16112. if (this._postProcesses.length > 0) {
  16113. this._postProcesses[0].markTextureDirty();
  16114. }
  16115. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  16116. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  16117. var cam = this._rigCameras[i];
  16118. var rigPostProcess = cam._rigPostProcess;
  16119. // for VR rig, there does not have to be a post process
  16120. if (rigPostProcess) {
  16121. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  16122. if (isPass) {
  16123. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  16124. cam.isIntermediate = this._postProcesses.length === 0;
  16125. }
  16126. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  16127. rigPostProcess.markTextureDirty();
  16128. }
  16129. else {
  16130. cam._postProcesses = this._postProcesses.slice(0);
  16131. }
  16132. }
  16133. };
  16134. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  16135. if (insertAt === void 0) { insertAt = null; }
  16136. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  16137. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  16138. return 0;
  16139. }
  16140. if (insertAt == null || insertAt < 0) {
  16141. this._postProcesses.push(postProcess);
  16142. }
  16143. else {
  16144. this._postProcesses.splice(insertAt, 0, postProcess);
  16145. }
  16146. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16147. return this._postProcesses.indexOf(postProcess);
  16148. };
  16149. Camera.prototype.detachPostProcess = function (postProcess) {
  16150. var idx = this._postProcesses.indexOf(postProcess);
  16151. if (idx !== -1) {
  16152. this._postProcesses.splice(idx, 1);
  16153. }
  16154. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  16155. };
  16156. Camera.prototype.getWorldMatrix = function () {
  16157. if (!this._worldMatrix) {
  16158. this._worldMatrix = BABYLON.Matrix.Identity();
  16159. }
  16160. var viewMatrix = this.getViewMatrix();
  16161. viewMatrix.invertToRef(this._worldMatrix);
  16162. return this._worldMatrix;
  16163. };
  16164. Camera.prototype._getViewMatrix = function () {
  16165. return BABYLON.Matrix.Identity();
  16166. };
  16167. Camera.prototype.getViewMatrix = function (force) {
  16168. if (!force && this._isSynchronizedViewMatrix()) {
  16169. return this._computedViewMatrix;
  16170. }
  16171. this.updateCache();
  16172. this._computedViewMatrix = this._getViewMatrix();
  16173. this._currentRenderId = this.getScene().getRenderId();
  16174. this._refreshFrustumPlanes = true;
  16175. if (!this.parent || !this.parent.getWorldMatrix) {
  16176. this._globalPosition.copyFrom(this.position);
  16177. }
  16178. else {
  16179. if (!this._worldMatrix) {
  16180. this._worldMatrix = BABYLON.Matrix.Identity();
  16181. }
  16182. this._computedViewMatrix.invertToRef(this._worldMatrix);
  16183. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  16184. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  16185. this._computedViewMatrix.invert();
  16186. this._markSyncedWithParent();
  16187. }
  16188. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  16189. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  16190. }
  16191. this.onViewMatrixChangedObservable.notifyObservers(this);
  16192. return this._computedViewMatrix;
  16193. };
  16194. Camera.prototype.freezeProjectionMatrix = function (projection) {
  16195. this._doNotComputeProjectionMatrix = true;
  16196. if (projection !== undefined) {
  16197. this._projectionMatrix = projection;
  16198. }
  16199. };
  16200. ;
  16201. Camera.prototype.unfreezeProjectionMatrix = function () {
  16202. this._doNotComputeProjectionMatrix = false;
  16203. };
  16204. ;
  16205. Camera.prototype.getProjectionMatrix = function (force) {
  16206. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  16207. return this._projectionMatrix;
  16208. }
  16209. // Cache
  16210. this._cache.mode = this.mode;
  16211. this._cache.minZ = this.minZ;
  16212. this._cache.maxZ = this.maxZ;
  16213. // Matrix
  16214. this._refreshFrustumPlanes = true;
  16215. var engine = this.getEngine();
  16216. var scene = this.getScene();
  16217. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  16218. this._cache.fov = this.fov;
  16219. this._cache.fovMode = this.fovMode;
  16220. this._cache.aspectRatio = engine.getAspectRatio(this);
  16221. if (this.minZ <= 0) {
  16222. this.minZ = 0.1;
  16223. }
  16224. if (scene.useRightHandedSystem) {
  16225. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16226. }
  16227. else {
  16228. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  16229. }
  16230. }
  16231. else {
  16232. var halfWidth = engine.getRenderWidth() / 2.0;
  16233. var halfHeight = engine.getRenderHeight() / 2.0;
  16234. if (scene.useRightHandedSystem) {
  16235. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16236. }
  16237. else {
  16238. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  16239. }
  16240. this._cache.orthoLeft = this.orthoLeft;
  16241. this._cache.orthoRight = this.orthoRight;
  16242. this._cache.orthoBottom = this.orthoBottom;
  16243. this._cache.orthoTop = this.orthoTop;
  16244. this._cache.renderWidth = engine.getRenderWidth();
  16245. this._cache.renderHeight = engine.getRenderHeight();
  16246. }
  16247. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  16248. return this._projectionMatrix;
  16249. };
  16250. Camera.prototype.getTranformationMatrix = function () {
  16251. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16252. return this._transformMatrix;
  16253. };
  16254. Camera.prototype.updateFrustumPlanes = function () {
  16255. if (!this._refreshFrustumPlanes) {
  16256. return;
  16257. }
  16258. this.getTranformationMatrix();
  16259. if (!this._frustumPlanes) {
  16260. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16261. }
  16262. else {
  16263. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16264. }
  16265. this._refreshFrustumPlanes = false;
  16266. };
  16267. Camera.prototype.isInFrustum = function (target) {
  16268. this.updateFrustumPlanes();
  16269. return target.isInFrustum(this._frustumPlanes);
  16270. };
  16271. Camera.prototype.isCompletelyInFrustum = function (target) {
  16272. this.updateFrustumPlanes();
  16273. return target.isCompletelyInFrustum(this._frustumPlanes);
  16274. };
  16275. Camera.prototype.getForwardRay = function (length, transform, origin) {
  16276. if (length === void 0) { length = 100; }
  16277. if (!transform) {
  16278. transform = this.getWorldMatrix();
  16279. }
  16280. if (!origin) {
  16281. origin = this.position;
  16282. }
  16283. var forward = new BABYLON.Vector3(0, 0, 1);
  16284. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  16285. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  16286. return new BABYLON.Ray(origin, direction, length);
  16287. };
  16288. Camera.prototype.dispose = function () {
  16289. // Observables
  16290. this.onViewMatrixChangedObservable.clear();
  16291. this.onProjectionMatrixChangedObservable.clear();
  16292. this.onAfterCheckInputsObservable.clear();
  16293. this.onRestoreStateObservable.clear();
  16294. // Inputs
  16295. if (this.inputs) {
  16296. this.inputs.clear();
  16297. }
  16298. // Animations
  16299. this.getScene().stopAnimation(this);
  16300. // Remove from scene
  16301. this.getScene().removeCamera(this);
  16302. while (this._rigCameras.length > 0) {
  16303. var camera = this._rigCameras.pop();
  16304. if (camera) {
  16305. camera.dispose();
  16306. }
  16307. }
  16308. // Postprocesses
  16309. if (this._rigPostProcess) {
  16310. this._rigPostProcess.dispose(this);
  16311. this._rigPostProcess = null;
  16312. this._postProcesses = [];
  16313. }
  16314. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16315. this._rigPostProcess = null;
  16316. this._postProcesses = [];
  16317. }
  16318. else {
  16319. var i = this._postProcesses.length;
  16320. while (--i >= 0) {
  16321. this._postProcesses[i].dispose(this);
  16322. }
  16323. }
  16324. // Render targets
  16325. var i = this.customRenderTargets.length;
  16326. while (--i >= 0) {
  16327. this.customRenderTargets[i].dispose();
  16328. }
  16329. this.customRenderTargets = [];
  16330. // Active Meshes
  16331. this._activeMeshes.dispose();
  16332. _super.prototype.dispose.call(this);
  16333. };
  16334. Object.defineProperty(Camera.prototype, "leftCamera", {
  16335. // ---- Camera rigs section ----
  16336. get: function () {
  16337. if (this._rigCameras.length < 1) {
  16338. return null;
  16339. }
  16340. return this._rigCameras[0];
  16341. },
  16342. enumerable: true,
  16343. configurable: true
  16344. });
  16345. Object.defineProperty(Camera.prototype, "rightCamera", {
  16346. get: function () {
  16347. if (this._rigCameras.length < 2) {
  16348. return null;
  16349. }
  16350. return this._rigCameras[1];
  16351. },
  16352. enumerable: true,
  16353. configurable: true
  16354. });
  16355. Camera.prototype.getLeftTarget = function () {
  16356. if (this._rigCameras.length < 1) {
  16357. return null;
  16358. }
  16359. return this._rigCameras[0].getTarget();
  16360. };
  16361. Camera.prototype.getRightTarget = function () {
  16362. if (this._rigCameras.length < 2) {
  16363. return null;
  16364. }
  16365. return this._rigCameras[1].getTarget();
  16366. };
  16367. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  16368. if (this.cameraRigMode === mode) {
  16369. return;
  16370. }
  16371. while (this._rigCameras.length > 0) {
  16372. var camera = this._rigCameras.pop();
  16373. if (camera) {
  16374. camera.dispose();
  16375. }
  16376. }
  16377. this.cameraRigMode = mode;
  16378. this._cameraRigParams = {};
  16379. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  16380. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  16381. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  16382. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  16383. // create the rig cameras, unless none
  16384. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  16385. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  16386. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  16387. if (leftCamera && rightCamera) {
  16388. this._rigCameras.push(leftCamera);
  16389. this._rigCameras.push(rightCamera);
  16390. }
  16391. }
  16392. switch (this.cameraRigMode) {
  16393. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16394. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16395. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  16396. break;
  16397. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16398. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16399. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16400. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16401. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  16402. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  16403. break;
  16404. case Camera.RIG_MODE_VR:
  16405. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  16406. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  16407. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16408. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16409. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  16410. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  16411. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  16412. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  16413. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16414. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16415. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  16416. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  16417. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  16418. if (metrics.compensateDistortion) {
  16419. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  16420. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  16421. }
  16422. break;
  16423. case Camera.RIG_MODE_WEBVR:
  16424. if (rigParams.vrDisplay) {
  16425. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  16426. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  16427. //Left eye
  16428. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  16429. this._rigCameras[0].setCameraRigParameter("left", true);
  16430. //leaving this for future reference
  16431. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  16432. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  16433. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  16434. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16435. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16436. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16437. this._rigCameras[0].parent = this;
  16438. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  16439. //Right eye
  16440. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  16441. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  16442. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  16443. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  16444. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  16445. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  16446. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  16447. this._rigCameras[1].parent = this;
  16448. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  16449. if (Camera.UseAlternateWebVRRendering) {
  16450. this._rigCameras[1]._skipRendering = true;
  16451. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  16452. }
  16453. }
  16454. break;
  16455. }
  16456. this._cascadePostProcessesToRigCams();
  16457. this.update();
  16458. };
  16459. Camera.prototype._getVRProjectionMatrix = function () {
  16460. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  16461. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  16462. return this._projectionMatrix;
  16463. };
  16464. Camera.prototype._updateCameraRotationMatrix = function () {
  16465. //Here for WebVR
  16466. };
  16467. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  16468. //Here for WebVR
  16469. };
  16470. /**
  16471. * This function MUST be overwritten by the different WebVR cameras available.
  16472. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16473. */
  16474. Camera.prototype._getWebVRProjectionMatrix = function () {
  16475. return BABYLON.Matrix.Identity();
  16476. };
  16477. /**
  16478. * This function MUST be overwritten by the different WebVR cameras available.
  16479. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  16480. */
  16481. Camera.prototype._getWebVRViewMatrix = function () {
  16482. return BABYLON.Matrix.Identity();
  16483. };
  16484. Camera.prototype.setCameraRigParameter = function (name, value) {
  16485. if (!this._cameraRigParams) {
  16486. this._cameraRigParams = {};
  16487. }
  16488. this._cameraRigParams[name] = value;
  16489. //provisionnally:
  16490. if (name === "interaxialDistance") {
  16491. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  16492. }
  16493. };
  16494. /**
  16495. * needs to be overridden by children so sub has required properties to be copied
  16496. */
  16497. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  16498. return null;
  16499. };
  16500. /**
  16501. * May need to be overridden by children
  16502. */
  16503. Camera.prototype._updateRigCameras = function () {
  16504. for (var i = 0; i < this._rigCameras.length; i++) {
  16505. this._rigCameras[i].minZ = this.minZ;
  16506. this._rigCameras[i].maxZ = this.maxZ;
  16507. this._rigCameras[i].fov = this.fov;
  16508. }
  16509. // only update viewport when ANAGLYPH
  16510. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  16511. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  16512. }
  16513. };
  16514. Camera.prototype._setupInputs = function () {
  16515. };
  16516. Camera.prototype.serialize = function () {
  16517. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16518. // Type
  16519. serializationObject.type = this.getClassName();
  16520. // Parent
  16521. if (this.parent) {
  16522. serializationObject.parentId = this.parent.id;
  16523. }
  16524. if (this.inputs) {
  16525. this.inputs.serialize(serializationObject);
  16526. }
  16527. // Animations
  16528. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16529. serializationObject.ranges = this.serializeAnimationRanges();
  16530. return serializationObject;
  16531. };
  16532. Camera.prototype.clone = function (name) {
  16533. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  16534. };
  16535. Camera.prototype.getDirection = function (localAxis) {
  16536. var result = BABYLON.Vector3.Zero();
  16537. this.getDirectionToRef(localAxis, result);
  16538. return result;
  16539. };
  16540. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  16541. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16542. };
  16543. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  16544. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  16545. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  16546. switch (type) {
  16547. case "ArcRotateCamera":
  16548. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  16549. case "DeviceOrientationCamera":
  16550. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  16551. case "FollowCamera":
  16552. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  16553. case "ArcFollowCamera":
  16554. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  16555. case "GamepadCamera":
  16556. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16557. case "TouchCamera":
  16558. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  16559. case "VirtualJoysticksCamera":
  16560. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  16561. case "WebVRFreeCamera":
  16562. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16563. case "WebVRGamepadCamera":
  16564. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16565. case "VRDeviceOrientationFreeCamera":
  16566. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  16567. case "VRDeviceOrientationGamepadCamera":
  16568. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  16569. case "AnaglyphArcRotateCamera":
  16570. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16571. case "AnaglyphFreeCamera":
  16572. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16573. case "AnaglyphGamepadCamera":
  16574. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16575. case "AnaglyphUniversalCamera":
  16576. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  16577. case "StereoscopicArcRotateCamera":
  16578. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16579. case "StereoscopicFreeCamera":
  16580. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16581. case "StereoscopicGamepadCamera":
  16582. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16583. case "StereoscopicUniversalCamera":
  16584. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  16585. case "FreeCamera":// Forcing Universal here
  16586. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16587. default:// Universal Camera is the default value
  16588. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  16589. }
  16590. };
  16591. Camera.Parse = function (parsedCamera, scene) {
  16592. var type = parsedCamera.type;
  16593. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  16594. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  16595. // Parent
  16596. if (parsedCamera.parentId) {
  16597. camera._waitingParentId = parsedCamera.parentId;
  16598. }
  16599. //If camera has an input manager, let it parse inputs settings
  16600. if (camera.inputs) {
  16601. camera.inputs.parse(parsedCamera);
  16602. camera._setupInputs();
  16603. }
  16604. if (camera.setPosition) {
  16605. camera.position.copyFromFloats(0, 0, 0);
  16606. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  16607. }
  16608. // Target
  16609. if (parsedCamera.target) {
  16610. if (camera.setTarget) {
  16611. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  16612. }
  16613. }
  16614. // Apply 3d rig, when found
  16615. if (parsedCamera.cameraRigMode) {
  16616. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  16617. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  16618. }
  16619. // Animations
  16620. if (parsedCamera.animations) {
  16621. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  16622. var parsedAnimation = parsedCamera.animations[animationIndex];
  16623. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16624. }
  16625. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  16626. }
  16627. if (parsedCamera.autoAnimate) {
  16628. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  16629. }
  16630. return camera;
  16631. };
  16632. // Statics
  16633. Camera._PERSPECTIVE_CAMERA = 0;
  16634. Camera._ORTHOGRAPHIC_CAMERA = 1;
  16635. Camera._FOVMODE_VERTICAL_FIXED = 0;
  16636. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  16637. Camera._RIG_MODE_NONE = 0;
  16638. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  16639. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  16640. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  16641. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  16642. Camera._RIG_MODE_VR = 20;
  16643. Camera._RIG_MODE_WEBVR = 21;
  16644. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  16645. Camera.UseAlternateWebVRRendering = false;
  16646. __decorate([
  16647. BABYLON.serializeAsVector3()
  16648. ], Camera.prototype, "position", void 0);
  16649. __decorate([
  16650. BABYLON.serializeAsVector3()
  16651. ], Camera.prototype, "upVector", void 0);
  16652. __decorate([
  16653. BABYLON.serialize()
  16654. ], Camera.prototype, "orthoLeft", void 0);
  16655. __decorate([
  16656. BABYLON.serialize()
  16657. ], Camera.prototype, "orthoRight", void 0);
  16658. __decorate([
  16659. BABYLON.serialize()
  16660. ], Camera.prototype, "orthoBottom", void 0);
  16661. __decorate([
  16662. BABYLON.serialize()
  16663. ], Camera.prototype, "orthoTop", void 0);
  16664. __decorate([
  16665. BABYLON.serialize()
  16666. ], Camera.prototype, "fov", void 0);
  16667. __decorate([
  16668. BABYLON.serialize()
  16669. ], Camera.prototype, "minZ", void 0);
  16670. __decorate([
  16671. BABYLON.serialize()
  16672. ], Camera.prototype, "maxZ", void 0);
  16673. __decorate([
  16674. BABYLON.serialize()
  16675. ], Camera.prototype, "inertia", void 0);
  16676. __decorate([
  16677. BABYLON.serialize()
  16678. ], Camera.prototype, "mode", void 0);
  16679. __decorate([
  16680. BABYLON.serialize()
  16681. ], Camera.prototype, "layerMask", void 0);
  16682. __decorate([
  16683. BABYLON.serialize()
  16684. ], Camera.prototype, "fovMode", void 0);
  16685. __decorate([
  16686. BABYLON.serialize()
  16687. ], Camera.prototype, "cameraRigMode", void 0);
  16688. __decorate([
  16689. BABYLON.serialize()
  16690. ], Camera.prototype, "interaxialDistance", void 0);
  16691. __decorate([
  16692. BABYLON.serialize()
  16693. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  16694. return Camera;
  16695. }(BABYLON.Node));
  16696. BABYLON.Camera = Camera;
  16697. })(BABYLON || (BABYLON = {}));
  16698. //# sourceMappingURL=babylon.camera.js.map
  16699. var BABYLON;
  16700. (function (BABYLON) {
  16701. var RenderingManager = /** @class */ (function () {
  16702. function RenderingManager(scene) {
  16703. this._renderingGroups = new Array();
  16704. this._autoClearDepthStencil = {};
  16705. this._customOpaqueSortCompareFn = {};
  16706. this._customAlphaTestSortCompareFn = {};
  16707. this._customTransparentSortCompareFn = {};
  16708. this._renderinGroupInfo = null;
  16709. this._scene = scene;
  16710. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16711. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16712. }
  16713. }
  16714. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16715. if (depth === void 0) { depth = true; }
  16716. if (stencil === void 0) { stencil = true; }
  16717. if (this._depthStencilBufferAlreadyCleaned) {
  16718. return;
  16719. }
  16720. this._scene.getEngine().clear(null, false, depth, stencil);
  16721. this._depthStencilBufferAlreadyCleaned = true;
  16722. };
  16723. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16724. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16725. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16726. var info = null;
  16727. if (observable) {
  16728. if (!this._renderinGroupInfo) {
  16729. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16730. }
  16731. info = this._renderinGroupInfo;
  16732. info.scene = this._scene;
  16733. info.camera = this._scene.activeCamera;
  16734. }
  16735. // Dispatch sprites
  16736. if (renderSprites) {
  16737. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16738. var manager = this._scene.spriteManagers[index];
  16739. this.dispatchSprites(manager);
  16740. }
  16741. }
  16742. // Render
  16743. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16744. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16745. var renderingGroup = this._renderingGroups[index];
  16746. if (!renderingGroup && !observable)
  16747. continue;
  16748. this._currentIndex = index;
  16749. var renderingGroupMask = 0;
  16750. // Fire PRECLEAR stage
  16751. if (observable && info) {
  16752. renderingGroupMask = Math.pow(2, index);
  16753. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16754. info.renderingGroupId = index;
  16755. observable.notifyObservers(info, renderingGroupMask);
  16756. }
  16757. // Clear depth/stencil if needed
  16758. if (RenderingManager.AUTOCLEAR) {
  16759. var autoClear = this._autoClearDepthStencil[index];
  16760. if (autoClear && autoClear.autoClear) {
  16761. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16762. }
  16763. }
  16764. if (observable && info) {
  16765. // Fire PREOPAQUE stage
  16766. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16767. observable.notifyObservers(info, renderingGroupMask);
  16768. // Fire PRETRANSPARENT stage
  16769. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16770. observable.notifyObservers(info, renderingGroupMask);
  16771. }
  16772. if (renderingGroup)
  16773. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16774. // Fire POSTTRANSPARENT stage
  16775. if (observable && info) {
  16776. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16777. observable.notifyObservers(info, renderingGroupMask);
  16778. }
  16779. }
  16780. };
  16781. RenderingManager.prototype.reset = function () {
  16782. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16783. var renderingGroup = this._renderingGroups[index];
  16784. if (renderingGroup) {
  16785. renderingGroup.prepare();
  16786. }
  16787. }
  16788. };
  16789. RenderingManager.prototype.dispose = function () {
  16790. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16791. var renderingGroup = this._renderingGroups[index];
  16792. if (renderingGroup) {
  16793. renderingGroup.dispose();
  16794. }
  16795. }
  16796. this._renderingGroups.length = 0;
  16797. };
  16798. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16799. if (!this._renderingGroups[renderingGroupId]) {
  16800. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16801. }
  16802. };
  16803. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16804. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16805. this._prepareRenderingGroup(renderingGroupId);
  16806. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16807. };
  16808. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16809. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16810. this._prepareRenderingGroup(renderingGroupId);
  16811. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16812. };
  16813. RenderingManager.prototype.dispatch = function (subMesh) {
  16814. var mesh = subMesh.getMesh();
  16815. var renderingGroupId = mesh.renderingGroupId || 0;
  16816. this._prepareRenderingGroup(renderingGroupId);
  16817. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16818. };
  16819. /**
  16820. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16821. * This allowed control for front to back rendering or reversly depending of the special needs.
  16822. *
  16823. * @param renderingGroupId The rendering group id corresponding to its index
  16824. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16825. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16826. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16827. */
  16828. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16829. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16830. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16831. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16832. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16833. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16834. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16835. if (this._renderingGroups[renderingGroupId]) {
  16836. var group = this._renderingGroups[renderingGroupId];
  16837. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16838. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16839. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16840. }
  16841. };
  16842. /**
  16843. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16844. *
  16845. * @param renderingGroupId The rendering group id corresponding to its index
  16846. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16847. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16848. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16849. */
  16850. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16851. if (depth === void 0) { depth = true; }
  16852. if (stencil === void 0) { stencil = true; }
  16853. this._autoClearDepthStencil[renderingGroupId] = {
  16854. autoClear: autoClearDepthStencil,
  16855. depth: depth,
  16856. stencil: stencil
  16857. };
  16858. };
  16859. /**
  16860. * The max id used for rendering groups (not included)
  16861. */
  16862. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16863. /**
  16864. * The min id used for rendering groups (included)
  16865. */
  16866. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16867. /**
  16868. * Used to globally prevent autoclearing scenes.
  16869. */
  16870. RenderingManager.AUTOCLEAR = true;
  16871. return RenderingManager;
  16872. }());
  16873. BABYLON.RenderingManager = RenderingManager;
  16874. })(BABYLON || (BABYLON = {}));
  16875. //# sourceMappingURL=babylon.renderingManager.js.map
  16876. var BABYLON;
  16877. (function (BABYLON) {
  16878. var RenderingGroup = /** @class */ (function () {
  16879. /**
  16880. * Creates a new rendering group.
  16881. * @param index The rendering group index
  16882. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16883. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16884. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16885. */
  16886. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16887. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16888. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16889. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16890. this.index = index;
  16891. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16892. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16893. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16894. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  16895. this._particleSystems = new BABYLON.SmartArray(256);
  16896. this._spriteManagers = new BABYLON.SmartArray(256);
  16897. this._edgesRenderers = new BABYLON.SmartArray(16);
  16898. this._scene = scene;
  16899. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16900. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16901. this.transparentSortCompareFn = transparentSortCompareFn;
  16902. }
  16903. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16904. /**
  16905. * Set the opaque sort comparison function.
  16906. * If null the sub meshes will be render in the order they were created
  16907. */
  16908. set: function (value) {
  16909. this._opaqueSortCompareFn = value;
  16910. if (value) {
  16911. this._renderOpaque = this.renderOpaqueSorted;
  16912. }
  16913. else {
  16914. this._renderOpaque = RenderingGroup.renderUnsorted;
  16915. }
  16916. },
  16917. enumerable: true,
  16918. configurable: true
  16919. });
  16920. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16921. /**
  16922. * Set the alpha test sort comparison function.
  16923. * If null the sub meshes will be render in the order they were created
  16924. */
  16925. set: function (value) {
  16926. this._alphaTestSortCompareFn = value;
  16927. if (value) {
  16928. this._renderAlphaTest = this.renderAlphaTestSorted;
  16929. }
  16930. else {
  16931. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16932. }
  16933. },
  16934. enumerable: true,
  16935. configurable: true
  16936. });
  16937. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16938. /**
  16939. * Set the transparent sort comparison function.
  16940. * If null the sub meshes will be render in the order they were created
  16941. */
  16942. set: function (value) {
  16943. if (value) {
  16944. this._transparentSortCompareFn = value;
  16945. }
  16946. else {
  16947. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16948. }
  16949. this._renderTransparent = this.renderTransparentSorted;
  16950. },
  16951. enumerable: true,
  16952. configurable: true
  16953. });
  16954. /**
  16955. * Render all the sub meshes contained in the group.
  16956. * @param customRenderFunction Used to override the default render behaviour of the group.
  16957. * @returns true if rendered some submeshes.
  16958. */
  16959. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16960. if (customRenderFunction) {
  16961. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  16962. return;
  16963. }
  16964. var engine = this._scene.getEngine();
  16965. // Depth only
  16966. if (this._depthOnlySubMeshes.length !== 0) {
  16967. engine.setAlphaTesting(true);
  16968. engine.setColorWrite(false);
  16969. this._renderAlphaTest(this._depthOnlySubMeshes);
  16970. engine.setAlphaTesting(false);
  16971. engine.setColorWrite(true);
  16972. }
  16973. // Opaque
  16974. if (this._opaqueSubMeshes.length !== 0) {
  16975. this._renderOpaque(this._opaqueSubMeshes);
  16976. }
  16977. // Alpha test
  16978. if (this._alphaTestSubMeshes.length !== 0) {
  16979. engine.setAlphaTesting(true);
  16980. this._renderAlphaTest(this._alphaTestSubMeshes);
  16981. engine.setAlphaTesting(false);
  16982. }
  16983. var stencilState = engine.getStencilBuffer();
  16984. engine.setStencilBuffer(false);
  16985. // Sprites
  16986. if (renderSprites) {
  16987. this._renderSprites();
  16988. }
  16989. // Particles
  16990. if (renderParticles) {
  16991. this._renderParticles(activeMeshes);
  16992. }
  16993. if (this.onBeforeTransparentRendering) {
  16994. this.onBeforeTransparentRendering();
  16995. }
  16996. // Transparent
  16997. if (this._transparentSubMeshes.length !== 0) {
  16998. this._renderTransparent(this._transparentSubMeshes);
  16999. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17000. }
  17001. // Set back stencil to false in case it changes before the edge renderer.
  17002. engine.setStencilBuffer(false);
  17003. // Edges
  17004. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17005. this._edgesRenderers.data[edgesRendererIndex].render();
  17006. }
  17007. // Restore Stencil state.
  17008. engine.setStencilBuffer(stencilState);
  17009. };
  17010. /**
  17011. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17012. * @param subMeshes The submeshes to render
  17013. */
  17014. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17015. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17016. };
  17017. /**
  17018. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17019. * @param subMeshes The submeshes to render
  17020. */
  17021. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17022. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17023. };
  17024. /**
  17025. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17026. * @param subMeshes The submeshes to render
  17027. */
  17028. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17029. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17030. };
  17031. /**
  17032. * Renders the submeshes in a specified order.
  17033. * @param subMeshes The submeshes to sort before render
  17034. * @param sortCompareFn The comparison function use to sort
  17035. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17036. * @param transparent Specifies to activate blending if true
  17037. */
  17038. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17039. var subIndex = 0;
  17040. var subMesh;
  17041. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17042. for (; subIndex < subMeshes.length; subIndex++) {
  17043. subMesh = subMeshes.data[subIndex];
  17044. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17045. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17046. }
  17047. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17048. if (sortCompareFn) {
  17049. sortedArray.sort(sortCompareFn);
  17050. }
  17051. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17052. subMesh = sortedArray[subIndex];
  17053. if (transparent) {
  17054. var material = subMesh.getMaterial();
  17055. if (material && material.needDepthPrePass) {
  17056. var engine = material.getScene().getEngine();
  17057. engine.setColorWrite(false);
  17058. engine.setAlphaTesting(true);
  17059. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17060. subMesh.render(false);
  17061. engine.setAlphaTesting(false);
  17062. engine.setColorWrite(true);
  17063. }
  17064. }
  17065. subMesh.render(transparent);
  17066. }
  17067. };
  17068. /**
  17069. * Renders the submeshes in the order they were dispatched (no sort applied).
  17070. * @param subMeshes The submeshes to render
  17071. */
  17072. RenderingGroup.renderUnsorted = function (subMeshes) {
  17073. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17074. var submesh = subMeshes.data[subIndex];
  17075. submesh.render(false);
  17076. }
  17077. };
  17078. /**
  17079. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17080. * are rendered back to front if in the same alpha index.
  17081. *
  17082. * @param a The first submesh
  17083. * @param b The second submesh
  17084. * @returns The result of the comparison
  17085. */
  17086. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17087. // Alpha index first
  17088. if (a._alphaIndex > b._alphaIndex) {
  17089. return 1;
  17090. }
  17091. if (a._alphaIndex < b._alphaIndex) {
  17092. return -1;
  17093. }
  17094. // Then distance to camera
  17095. return RenderingGroup.backToFrontSortCompare(a, b);
  17096. };
  17097. /**
  17098. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17099. * are rendered back to front.
  17100. *
  17101. * @param a The first submesh
  17102. * @param b The second submesh
  17103. * @returns The result of the comparison
  17104. */
  17105. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17106. // Then distance to camera
  17107. if (a._distanceToCamera < b._distanceToCamera) {
  17108. return 1;
  17109. }
  17110. if (a._distanceToCamera > b._distanceToCamera) {
  17111. return -1;
  17112. }
  17113. return 0;
  17114. };
  17115. /**
  17116. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17117. * are rendered front to back (prevent overdraw).
  17118. *
  17119. * @param a The first submesh
  17120. * @param b The second submesh
  17121. * @returns The result of the comparison
  17122. */
  17123. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17124. // Then distance to camera
  17125. if (a._distanceToCamera < b._distanceToCamera) {
  17126. return -1;
  17127. }
  17128. if (a._distanceToCamera > b._distanceToCamera) {
  17129. return 1;
  17130. }
  17131. return 0;
  17132. };
  17133. /**
  17134. * Resets the different lists of submeshes to prepare a new frame.
  17135. */
  17136. RenderingGroup.prototype.prepare = function () {
  17137. this._opaqueSubMeshes.reset();
  17138. this._transparentSubMeshes.reset();
  17139. this._alphaTestSubMeshes.reset();
  17140. this._depthOnlySubMeshes.reset();
  17141. this._particleSystems.reset();
  17142. this._spriteManagers.reset();
  17143. this._edgesRenderers.reset();
  17144. };
  17145. RenderingGroup.prototype.dispose = function () {
  17146. this._opaqueSubMeshes.dispose();
  17147. this._transparentSubMeshes.dispose();
  17148. this._alphaTestSubMeshes.dispose();
  17149. this._depthOnlySubMeshes.dispose();
  17150. this._particleSystems.dispose();
  17151. this._spriteManagers.dispose();
  17152. this._edgesRenderers.dispose();
  17153. };
  17154. /**
  17155. * Inserts the submesh in its correct queue depending on its material.
  17156. * @param subMesh The submesh to dispatch
  17157. */
  17158. RenderingGroup.prototype.dispatch = function (subMesh) {
  17159. var material = subMesh.getMaterial();
  17160. var mesh = subMesh.getMesh();
  17161. if (!material) {
  17162. return;
  17163. }
  17164. if (material.needAlphaBlending() || material.needAlphaBlendingForMesh(mesh)) {
  17165. this._transparentSubMeshes.push(subMesh);
  17166. }
  17167. else if (material.needAlphaTesting()) {
  17168. if (material.needDepthPrePass) {
  17169. this._depthOnlySubMeshes.push(subMesh);
  17170. }
  17171. this._alphaTestSubMeshes.push(subMesh);
  17172. }
  17173. else {
  17174. if (material.needDepthPrePass) {
  17175. this._depthOnlySubMeshes.push(subMesh);
  17176. }
  17177. this._opaqueSubMeshes.push(subMesh); // Opaque
  17178. }
  17179. if (mesh._edgesRenderer) {
  17180. this._edgesRenderers.push(mesh._edgesRenderer);
  17181. }
  17182. };
  17183. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17184. this._spriteManagers.push(spriteManager);
  17185. };
  17186. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17187. this._particleSystems.push(particleSystem);
  17188. };
  17189. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17190. if (this._particleSystems.length === 0) {
  17191. return;
  17192. }
  17193. // Particles
  17194. var activeCamera = this._scene.activeCamera;
  17195. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  17196. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17197. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17198. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17199. continue;
  17200. }
  17201. var emitter = particleSystem.emitter;
  17202. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  17203. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17204. }
  17205. }
  17206. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  17207. };
  17208. RenderingGroup.prototype._renderSprites = function () {
  17209. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17210. return;
  17211. }
  17212. // Sprites
  17213. var activeCamera = this._scene.activeCamera;
  17214. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  17215. for (var id = 0; id < this._spriteManagers.length; id++) {
  17216. var spriteManager = this._spriteManagers.data[id];
  17217. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17218. spriteManager.render();
  17219. }
  17220. }
  17221. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  17222. };
  17223. return RenderingGroup;
  17224. }());
  17225. BABYLON.RenderingGroup = RenderingGroup;
  17226. })(BABYLON || (BABYLON = {}));
  17227. //# sourceMappingURL=babylon.renderingGroup.js.map
  17228. var BABYLON;
  17229. (function (BABYLON) {
  17230. var ClickInfo = /** @class */ (function () {
  17231. function ClickInfo() {
  17232. this._singleClick = false;
  17233. this._doubleClick = false;
  17234. this._hasSwiped = false;
  17235. this._ignore = false;
  17236. }
  17237. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  17238. get: function () {
  17239. return this._singleClick;
  17240. },
  17241. set: function (b) {
  17242. this._singleClick = b;
  17243. },
  17244. enumerable: true,
  17245. configurable: true
  17246. });
  17247. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  17248. get: function () {
  17249. return this._doubleClick;
  17250. },
  17251. set: function (b) {
  17252. this._doubleClick = b;
  17253. },
  17254. enumerable: true,
  17255. configurable: true
  17256. });
  17257. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  17258. get: function () {
  17259. return this._hasSwiped;
  17260. },
  17261. set: function (b) {
  17262. this._hasSwiped = b;
  17263. },
  17264. enumerable: true,
  17265. configurable: true
  17266. });
  17267. Object.defineProperty(ClickInfo.prototype, "ignore", {
  17268. get: function () {
  17269. return this._ignore;
  17270. },
  17271. set: function (b) {
  17272. this._ignore = b;
  17273. },
  17274. enumerable: true,
  17275. configurable: true
  17276. });
  17277. return ClickInfo;
  17278. }());
  17279. /**
  17280. * This class is used by the onRenderingGroupObservable
  17281. */
  17282. var RenderingGroupInfo = /** @class */ (function () {
  17283. function RenderingGroupInfo() {
  17284. }
  17285. /**
  17286. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17287. * This stage will be fired no matter what
  17288. */
  17289. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17290. /**
  17291. * Called before opaque object are rendered.
  17292. * This stage will be fired only if there's 3D Opaque content to render
  17293. */
  17294. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17295. /**
  17296. * Called after the opaque objects are rendered and before the transparent ones
  17297. * This stage will be fired only if there's 3D transparent content to render
  17298. */
  17299. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17300. /**
  17301. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17302. * This stage will be fired no matter what
  17303. */
  17304. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17305. return RenderingGroupInfo;
  17306. }());
  17307. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17308. /**
  17309. * Represents a scene to be rendered by the engine.
  17310. * @see http://doc.babylonjs.com/page.php?p=21911
  17311. */
  17312. var Scene = /** @class */ (function () {
  17313. /**
  17314. * @constructor
  17315. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17316. */
  17317. function Scene(engine) {
  17318. // Members
  17319. this.autoClear = true;
  17320. this.autoClearDepthAndStencil = true;
  17321. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17322. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17323. this.forceWireframe = false;
  17324. this._forcePointsCloud = false;
  17325. this.forceShowBoundingBoxes = false;
  17326. this.animationsEnabled = true;
  17327. this.constantlyUpdateMeshUnderPointer = false;
  17328. this.hoverCursor = "pointer";
  17329. this.defaultCursor = "";
  17330. /**
  17331. * This is used to call preventDefault() on pointer down
  17332. * in order to block unwanted artifacts like system double clicks
  17333. */
  17334. this.preventDefaultOnPointerDown = true;
  17335. // Metadata
  17336. this.metadata = null;
  17337. /**
  17338. * An event triggered when the scene is disposed.
  17339. * @type {BABYLON.Observable}
  17340. */
  17341. this.onDisposeObservable = new BABYLON.Observable();
  17342. /**
  17343. * An event triggered before rendering the scene (right after animations and physics)
  17344. * @type {BABYLON.Observable}
  17345. */
  17346. this.onBeforeRenderObservable = new BABYLON.Observable();
  17347. /**
  17348. * An event triggered after rendering the scene
  17349. * @type {BABYLON.Observable}
  17350. */
  17351. this.onAfterRenderObservable = new BABYLON.Observable();
  17352. /**
  17353. * An event triggered before animating the scene
  17354. * @type {BABYLON.Observable}
  17355. */
  17356. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  17357. /**
  17358. * An event triggered after animations processing
  17359. * @type {BABYLON.Observable}
  17360. */
  17361. this.onAfterAnimationsObservable = new BABYLON.Observable();
  17362. /**
  17363. * An event triggered before draw calls are ready to be sent
  17364. * @type {BABYLON.Observable}
  17365. */
  17366. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  17367. /**
  17368. * An event triggered after draw calls have been sent
  17369. * @type {BABYLON.Observable}
  17370. */
  17371. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  17372. /**
  17373. * An event triggered when physic simulation is about to be run
  17374. * @type {BABYLON.Observable}
  17375. */
  17376. this.onBeforePhysicsObservable = new BABYLON.Observable();
  17377. /**
  17378. * An event triggered when physic simulation has been done
  17379. * @type {BABYLON.Observable}
  17380. */
  17381. this.onAfterPhysicsObservable = new BABYLON.Observable();
  17382. /**
  17383. * An event triggered when the scene is ready
  17384. * @type {BABYLON.Observable}
  17385. */
  17386. this.onReadyObservable = new BABYLON.Observable();
  17387. /**
  17388. * An event triggered before rendering a camera
  17389. * @type {BABYLON.Observable}
  17390. */
  17391. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17392. /**
  17393. * An event triggered after rendering a camera
  17394. * @type {BABYLON.Observable}
  17395. */
  17396. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17397. /**
  17398. * An event triggered when active meshes evaluation is about to start
  17399. * @type {BABYLON.Observable}
  17400. */
  17401. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17402. /**
  17403. * An event triggered when active meshes evaluation is done
  17404. * @type {BABYLON.Observable}
  17405. */
  17406. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  17407. /**
  17408. * An event triggered when particles rendering is about to start
  17409. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17410. * @type {BABYLON.Observable}
  17411. */
  17412. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  17413. /**
  17414. * An event triggered when particles rendering is done
  17415. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  17416. * @type {BABYLON.Observable}
  17417. */
  17418. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  17419. /**
  17420. * An event triggered when sprites rendering is about to start
  17421. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17422. * @type {BABYLON.Observable}
  17423. */
  17424. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  17425. /**
  17426. * An event triggered when sprites rendering is done
  17427. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  17428. * @type {BABYLON.Observable}
  17429. */
  17430. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  17431. /**
  17432. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  17433. * @type {BABYLON.Observable}
  17434. */
  17435. this.onDataLoadedObservable = new BABYLON.Observable();
  17436. /**
  17437. * An event triggered when a camera is created
  17438. * @type {BABYLON.Observable}
  17439. */
  17440. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17441. /**
  17442. * An event triggered when a camera is removed
  17443. * @type {BABYLON.Observable}
  17444. */
  17445. this.onCameraRemovedObservable = new BABYLON.Observable();
  17446. /**
  17447. * An event triggered when a light is created
  17448. * @type {BABYLON.Observable}
  17449. */
  17450. this.onNewLightAddedObservable = new BABYLON.Observable();
  17451. /**
  17452. * An event triggered when a light is removed
  17453. * @type {BABYLON.Observable}
  17454. */
  17455. this.onLightRemovedObservable = new BABYLON.Observable();
  17456. /**
  17457. * An event triggered when a geometry is created
  17458. * @type {BABYLON.Observable}
  17459. */
  17460. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17461. /**
  17462. * An event triggered when a geometry is removed
  17463. * @type {BABYLON.Observable}
  17464. */
  17465. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17466. /**
  17467. * An event triggered when a mesh is created
  17468. * @type {BABYLON.Observable}
  17469. */
  17470. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17471. /**
  17472. * An event triggered when a mesh is removed
  17473. * @type {BABYLON.Observable}
  17474. */
  17475. this.onMeshRemovedObservable = new BABYLON.Observable();
  17476. /**
  17477. * An event triggered when render targets are about to be rendered
  17478. * Can happen multiple times per frame.
  17479. * @type {BABYLON.Observable}
  17480. */
  17481. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  17482. /**
  17483. * An event triggered when render targets were rendered.
  17484. * Can happen multiple times per frame.
  17485. * @type {BABYLON.Observable}
  17486. */
  17487. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  17488. /**
  17489. * An event triggered before calculating deterministic simulation step
  17490. * @type {BABYLON.Observable}
  17491. */
  17492. this.onBeforeStepObservable = new BABYLON.Observable();
  17493. /**
  17494. * An event triggered after calculating deterministic simulation step
  17495. * @type {BABYLON.Observable}
  17496. */
  17497. this.onAfterStepObservable = new BABYLON.Observable();
  17498. /**
  17499. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17500. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17501. * 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)
  17502. */
  17503. this.onRenderingGroupObservable = new BABYLON.Observable();
  17504. // Animations
  17505. this.animations = [];
  17506. /**
  17507. * 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).
  17508. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  17509. */
  17510. this.onPrePointerObservable = new BABYLON.Observable();
  17511. /**
  17512. * Observable event triggered each time an input event is received from the rendering canvas
  17513. */
  17514. this.onPointerObservable = new BABYLON.Observable();
  17515. this._meshPickProceed = false;
  17516. this._previousHasSwiped = false;
  17517. this._currentPickResult = null;
  17518. this._previousPickResult = null;
  17519. this._totalPointersPressed = 0;
  17520. this._doubleClickOccured = false;
  17521. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  17522. this.cameraToUseForPointers = null;
  17523. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17524. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  17525. this._startingPointerTime = 0;
  17526. this._previousStartingPointerTime = 0;
  17527. // Deterministic lockstep
  17528. this._timeAccumulator = 0;
  17529. this._currentStepId = 0;
  17530. this._currentInternalStep = 0;
  17531. // Keyboard
  17532. /**
  17533. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  17534. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  17535. */
  17536. this.onPreKeyboardObservable = new BABYLON.Observable();
  17537. /**
  17538. * Observable event triggered each time an keyboard event is received from the hosting window
  17539. */
  17540. this.onKeyboardObservable = new BABYLON.Observable();
  17541. // Coordinate system
  17542. /**
  17543. * use right-handed coordinate system on this scene.
  17544. * @type {boolean}
  17545. */
  17546. this._useRightHandedSystem = false;
  17547. // Fog
  17548. this._fogEnabled = true;
  17549. this._fogMode = Scene.FOGMODE_NONE;
  17550. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17551. this.fogDensity = 0.1;
  17552. this.fogStart = 0;
  17553. this.fogEnd = 1000.0;
  17554. // Lights
  17555. /**
  17556. * is shadow enabled on this scene.
  17557. * @type {boolean}
  17558. */
  17559. this._shadowsEnabled = true;
  17560. /**
  17561. * is light enabled on this scene.
  17562. * @type {boolean}
  17563. */
  17564. this._lightsEnabled = true;
  17565. /**
  17566. * All of the lights added to this scene.
  17567. * @see BABYLON.Light
  17568. * @type {BABYLON.Light[]}
  17569. */
  17570. this.lights = new Array();
  17571. // Cameras
  17572. /** All of the cameras added to this scene. */
  17573. this.cameras = new Array();
  17574. /** All of the active cameras added to this scene. */
  17575. this.activeCameras = new Array();
  17576. // Meshes
  17577. /**
  17578. * All of the (abstract) meshes added to this scene.
  17579. * @see BABYLON.AbstractMesh
  17580. * @type {BABYLON.AbstractMesh[]}
  17581. */
  17582. this.meshes = new Array();
  17583. // Geometries
  17584. this._geometries = new Array();
  17585. this.materials = new Array();
  17586. this.multiMaterials = new Array();
  17587. // Textures
  17588. this._texturesEnabled = true;
  17589. this.textures = new Array();
  17590. // Particles
  17591. this.particlesEnabled = true;
  17592. this.particleSystems = new Array();
  17593. // Sprites
  17594. this.spritesEnabled = true;
  17595. this.spriteManagers = new Array();
  17596. // Layers
  17597. this.layers = new Array();
  17598. this.highlightLayers = new Array();
  17599. // Skeletons
  17600. this._skeletonsEnabled = true;
  17601. this.skeletons = new Array();
  17602. // Morph targets
  17603. this.morphTargetManagers = new Array();
  17604. // Lens flares
  17605. this.lensFlaresEnabled = true;
  17606. this.lensFlareSystems = new Array();
  17607. // Collisions
  17608. this.collisionsEnabled = true;
  17609. /** Defines the gravity applied to this scene */
  17610. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17611. // Postprocesses
  17612. this.postProcesses = new Array();
  17613. this.postProcessesEnabled = true;
  17614. // Customs render targets
  17615. this.renderTargetsEnabled = true;
  17616. this.dumpNextRenderTargets = false;
  17617. this.customRenderTargets = new Array();
  17618. // Imported meshes
  17619. this.importedMeshesFiles = new Array();
  17620. // Probes
  17621. this.probesEnabled = true;
  17622. this.reflectionProbes = new Array();
  17623. this._actionManagers = new Array();
  17624. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  17625. // Procedural textures
  17626. this.proceduralTexturesEnabled = true;
  17627. this._proceduralTextures = new Array();
  17628. this.soundTracks = new Array();
  17629. this._audioEnabled = true;
  17630. this._headphone = false;
  17631. // Performance counters
  17632. this._totalVertices = new BABYLON.PerfCounter();
  17633. this._activeIndices = new BABYLON.PerfCounter();
  17634. this._activeParticles = new BABYLON.PerfCounter();
  17635. this._activeBones = new BABYLON.PerfCounter();
  17636. this._animationTime = 0;
  17637. this.animationTimeScale = 1;
  17638. this._renderId = 0;
  17639. this._executeWhenReadyTimeoutId = -1;
  17640. this._intermediateRendering = false;
  17641. this._viewUpdateFlag = -1;
  17642. this._projectionUpdateFlag = -1;
  17643. this._alternateViewUpdateFlag = -1;
  17644. this._alternateProjectionUpdateFlag = -1;
  17645. this._toBeDisposed = new BABYLON.SmartArray(256);
  17646. this._pendingData = new Array();
  17647. this._isDisposed = false;
  17648. this._activeMeshes = new BABYLON.SmartArray(256);
  17649. this._processedMaterials = new BABYLON.SmartArray(256);
  17650. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  17651. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17652. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  17653. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  17654. this._activeAnimatables = new Array();
  17655. this._transformMatrix = BABYLON.Matrix.Zero();
  17656. this._useAlternateCameraConfiguration = false;
  17657. this._alternateRendering = false;
  17658. this.requireLightSorting = false;
  17659. this._activeMeshesFrozen = false;
  17660. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  17661. this._engine.scenes.push(this);
  17662. this._uid = null;
  17663. this._renderingManager = new BABYLON.RenderingManager(this);
  17664. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17665. if (BABYLON.OutlineRenderer) {
  17666. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17667. }
  17668. if (BABYLON.Tools.IsWindowObjectExist()) {
  17669. this.attachControl();
  17670. }
  17671. //simplification queue
  17672. if (BABYLON.SimplificationQueue) {
  17673. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17674. }
  17675. //collision coordinator initialization. For now legacy per default.
  17676. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17677. // Uniform Buffer
  17678. this._createUbo();
  17679. // Default Image processing definition.
  17680. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  17681. }
  17682. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17683. /** The fog is deactivated */
  17684. get: function () {
  17685. return Scene._FOGMODE_NONE;
  17686. },
  17687. enumerable: true,
  17688. configurable: true
  17689. });
  17690. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17691. /** The fog density is following an exponential function */
  17692. get: function () {
  17693. return Scene._FOGMODE_EXP;
  17694. },
  17695. enumerable: true,
  17696. configurable: true
  17697. });
  17698. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17699. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  17700. get: function () {
  17701. return Scene._FOGMODE_EXP2;
  17702. },
  17703. enumerable: true,
  17704. configurable: true
  17705. });
  17706. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17707. /** The fog density is following a linear function. */
  17708. get: function () {
  17709. return Scene._FOGMODE_LINEAR;
  17710. },
  17711. enumerable: true,
  17712. configurable: true
  17713. });
  17714. Object.defineProperty(Scene.prototype, "environmentTexture", {
  17715. /**
  17716. * Texture used in all pbr material as the reflection texture.
  17717. * As in the majority of the scene they are the same (exception for multi room and so on),
  17718. * this is easier to reference from here than from all the materials.
  17719. */
  17720. get: function () {
  17721. return this._environmentTexture;
  17722. },
  17723. /**
  17724. * Texture used in all pbr material as the reflection texture.
  17725. * As in the majority of the scene they are the same (exception for multi room and so on),
  17726. * this is easier to set here than in all the materials.
  17727. */
  17728. set: function (value) {
  17729. if (this._environmentTexture === value) {
  17730. return;
  17731. }
  17732. this._environmentTexture = value;
  17733. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17734. },
  17735. enumerable: true,
  17736. configurable: true
  17737. });
  17738. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  17739. /**
  17740. * Default image processing configuration used either in the rendering
  17741. * Forward main pass or through the imageProcessingPostProcess if present.
  17742. * As in the majority of the scene they are the same (exception for multi camera),
  17743. * this is easier to reference from here than from all the materials and post process.
  17744. *
  17745. * No setter as we it is a shared configuration, you can set the values instead.
  17746. */
  17747. get: function () {
  17748. return this._imageProcessingConfiguration;
  17749. },
  17750. enumerable: true,
  17751. configurable: true
  17752. });
  17753. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  17754. get: function () {
  17755. return this._forcePointsCloud;
  17756. },
  17757. set: function (value) {
  17758. if (this._forcePointsCloud === value) {
  17759. return;
  17760. }
  17761. this._forcePointsCloud = value;
  17762. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17763. },
  17764. enumerable: true,
  17765. configurable: true
  17766. });
  17767. Object.defineProperty(Scene.prototype, "onDispose", {
  17768. /** A function to be executed when this scene is disposed. */
  17769. set: function (callback) {
  17770. if (this._onDisposeObserver) {
  17771. this.onDisposeObservable.remove(this._onDisposeObserver);
  17772. }
  17773. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17774. },
  17775. enumerable: true,
  17776. configurable: true
  17777. });
  17778. Object.defineProperty(Scene.prototype, "beforeRender", {
  17779. /** A function to be executed before rendering this scene */
  17780. set: function (callback) {
  17781. if (this._onBeforeRenderObserver) {
  17782. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17783. }
  17784. if (callback) {
  17785. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17786. }
  17787. },
  17788. enumerable: true,
  17789. configurable: true
  17790. });
  17791. Object.defineProperty(Scene.prototype, "afterRender", {
  17792. /** A function to be executed after rendering this scene */
  17793. set: function (callback) {
  17794. if (this._onAfterRenderObserver) {
  17795. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17796. }
  17797. if (callback) {
  17798. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17799. }
  17800. },
  17801. enumerable: true,
  17802. configurable: true
  17803. });
  17804. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17805. set: function (callback) {
  17806. if (this._onBeforeCameraRenderObserver) {
  17807. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17808. }
  17809. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17810. },
  17811. enumerable: true,
  17812. configurable: true
  17813. });
  17814. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17815. set: function (callback) {
  17816. if (this._onAfterCameraRenderObserver) {
  17817. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17818. }
  17819. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17820. },
  17821. enumerable: true,
  17822. configurable: true
  17823. });
  17824. Object.defineProperty(Scene.prototype, "gamepadManager", {
  17825. get: function () {
  17826. if (!this._gamepadManager) {
  17827. this._gamepadManager = new BABYLON.GamepadManager();
  17828. }
  17829. return this._gamepadManager;
  17830. },
  17831. enumerable: true,
  17832. configurable: true
  17833. });
  17834. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17835. get: function () {
  17836. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17837. },
  17838. enumerable: true,
  17839. configurable: true
  17840. });
  17841. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  17842. get: function () {
  17843. return this._useRightHandedSystem;
  17844. },
  17845. set: function (value) {
  17846. if (this._useRightHandedSystem === value) {
  17847. return;
  17848. }
  17849. this._useRightHandedSystem = value;
  17850. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17851. },
  17852. enumerable: true,
  17853. configurable: true
  17854. });
  17855. Scene.prototype.setStepId = function (newStepId) {
  17856. this._currentStepId = newStepId;
  17857. };
  17858. ;
  17859. Scene.prototype.getStepId = function () {
  17860. return this._currentStepId;
  17861. };
  17862. ;
  17863. Scene.prototype.getInternalStep = function () {
  17864. return this._currentInternalStep;
  17865. };
  17866. ;
  17867. Object.defineProperty(Scene.prototype, "fogEnabled", {
  17868. get: function () {
  17869. return this._fogEnabled;
  17870. },
  17871. /**
  17872. * is fog enabled on this scene.
  17873. */
  17874. set: function (value) {
  17875. if (this._fogEnabled === value) {
  17876. return;
  17877. }
  17878. this._fogEnabled = value;
  17879. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17880. },
  17881. enumerable: true,
  17882. configurable: true
  17883. });
  17884. Object.defineProperty(Scene.prototype, "fogMode", {
  17885. get: function () {
  17886. return this._fogMode;
  17887. },
  17888. set: function (value) {
  17889. if (this._fogMode === value) {
  17890. return;
  17891. }
  17892. this._fogMode = value;
  17893. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  17894. },
  17895. enumerable: true,
  17896. configurable: true
  17897. });
  17898. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  17899. get: function () {
  17900. return this._shadowsEnabled;
  17901. },
  17902. set: function (value) {
  17903. if (this._shadowsEnabled === value) {
  17904. return;
  17905. }
  17906. this._shadowsEnabled = value;
  17907. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17908. },
  17909. enumerable: true,
  17910. configurable: true
  17911. });
  17912. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  17913. get: function () {
  17914. return this._lightsEnabled;
  17915. },
  17916. set: function (value) {
  17917. if (this._lightsEnabled === value) {
  17918. return;
  17919. }
  17920. this._lightsEnabled = value;
  17921. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  17922. },
  17923. enumerable: true,
  17924. configurable: true
  17925. });
  17926. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17927. /** The default material used on meshes when no material is affected */
  17928. get: function () {
  17929. if (!this._defaultMaterial) {
  17930. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17931. }
  17932. return this._defaultMaterial;
  17933. },
  17934. /** The default material used on meshes when no material is affected */
  17935. set: function (value) {
  17936. this._defaultMaterial = value;
  17937. },
  17938. enumerable: true,
  17939. configurable: true
  17940. });
  17941. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  17942. get: function () {
  17943. return this._texturesEnabled;
  17944. },
  17945. set: function (value) {
  17946. if (this._texturesEnabled === value) {
  17947. return;
  17948. }
  17949. this._texturesEnabled = value;
  17950. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17951. },
  17952. enumerable: true,
  17953. configurable: true
  17954. });
  17955. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  17956. get: function () {
  17957. return this._skeletonsEnabled;
  17958. },
  17959. set: function (value) {
  17960. if (this._skeletonsEnabled === value) {
  17961. return;
  17962. }
  17963. this._skeletonsEnabled = value;
  17964. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  17965. },
  17966. enumerable: true,
  17967. configurable: true
  17968. });
  17969. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  17970. get: function () {
  17971. if (!this._postProcessRenderPipelineManager) {
  17972. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17973. }
  17974. return this._postProcessRenderPipelineManager;
  17975. },
  17976. enumerable: true,
  17977. configurable: true
  17978. });
  17979. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  17980. get: function () {
  17981. if (!this._mainSoundTrack) {
  17982. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17983. }
  17984. return this._mainSoundTrack;
  17985. },
  17986. enumerable: true,
  17987. configurable: true
  17988. });
  17989. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  17990. get: function () {
  17991. return this._alternateRendering;
  17992. },
  17993. enumerable: true,
  17994. configurable: true
  17995. });
  17996. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17997. get: function () {
  17998. return this._frustumPlanes;
  17999. },
  18000. enumerable: true,
  18001. configurable: true
  18002. });
  18003. Object.defineProperty(Scene.prototype, "debugLayer", {
  18004. // Properties
  18005. get: function () {
  18006. if (!this._debugLayer) {
  18007. this._debugLayer = new BABYLON.DebugLayer(this);
  18008. }
  18009. return this._debugLayer;
  18010. },
  18011. enumerable: true,
  18012. configurable: true
  18013. });
  18014. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18015. get: function () {
  18016. return this._workerCollisions;
  18017. },
  18018. set: function (enabled) {
  18019. if (!BABYLON.CollisionCoordinatorLegacy) {
  18020. return;
  18021. }
  18022. enabled = (enabled && !!Worker);
  18023. this._workerCollisions = enabled;
  18024. if (this.collisionCoordinator) {
  18025. this.collisionCoordinator.destroy();
  18026. }
  18027. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  18028. this.collisionCoordinator.init(this);
  18029. },
  18030. enumerable: true,
  18031. configurable: true
  18032. });
  18033. Object.defineProperty(Scene.prototype, "selectionOctree", {
  18034. get: function () {
  18035. return this._selectionOctree;
  18036. },
  18037. enumerable: true,
  18038. configurable: true
  18039. });
  18040. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  18041. /**
  18042. * The mesh that is currently under the pointer.
  18043. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  18044. */
  18045. get: function () {
  18046. return this._pointerOverMesh;
  18047. },
  18048. enumerable: true,
  18049. configurable: true
  18050. });
  18051. Object.defineProperty(Scene.prototype, "pointerX", {
  18052. /**
  18053. * Current on-screen X position of the pointer
  18054. * @return {number} X position of the pointer
  18055. */
  18056. get: function () {
  18057. return this._pointerX;
  18058. },
  18059. enumerable: true,
  18060. configurable: true
  18061. });
  18062. Object.defineProperty(Scene.prototype, "pointerY", {
  18063. /**
  18064. * Current on-screen Y position of the pointer
  18065. * @return {number} Y position of the pointer
  18066. */
  18067. get: function () {
  18068. return this._pointerY;
  18069. },
  18070. enumerable: true,
  18071. configurable: true
  18072. });
  18073. Scene.prototype.getCachedMaterial = function () {
  18074. return this._cachedMaterial;
  18075. };
  18076. Scene.prototype.getCachedEffect = function () {
  18077. return this._cachedEffect;
  18078. };
  18079. Scene.prototype.getCachedVisibility = function () {
  18080. return this._cachedVisibility;
  18081. };
  18082. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  18083. if (visibility === void 0) { visibility = 1; }
  18084. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  18085. };
  18086. Scene.prototype.getBoundingBoxRenderer = function () {
  18087. if (!this._boundingBoxRenderer) {
  18088. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  18089. }
  18090. return this._boundingBoxRenderer;
  18091. };
  18092. Scene.prototype.getOutlineRenderer = function () {
  18093. return this._outlineRenderer;
  18094. };
  18095. Scene.prototype.getEngine = function () {
  18096. return this._engine;
  18097. };
  18098. Scene.prototype.getTotalVertices = function () {
  18099. return this._totalVertices.current;
  18100. };
  18101. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  18102. get: function () {
  18103. return this._totalVertices;
  18104. },
  18105. enumerable: true,
  18106. configurable: true
  18107. });
  18108. Scene.prototype.getActiveIndices = function () {
  18109. return this._activeIndices.current;
  18110. };
  18111. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  18112. get: function () {
  18113. return this._activeIndices;
  18114. },
  18115. enumerable: true,
  18116. configurable: true
  18117. });
  18118. Scene.prototype.getActiveParticles = function () {
  18119. return this._activeParticles.current;
  18120. };
  18121. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  18122. get: function () {
  18123. return this._activeParticles;
  18124. },
  18125. enumerable: true,
  18126. configurable: true
  18127. });
  18128. Scene.prototype.getActiveBones = function () {
  18129. return this._activeBones.current;
  18130. };
  18131. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  18132. get: function () {
  18133. return this._activeBones;
  18134. },
  18135. enumerable: true,
  18136. configurable: true
  18137. });
  18138. // Stats
  18139. Scene.prototype.getInterFramePerfCounter = function () {
  18140. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18141. return 0;
  18142. };
  18143. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  18144. get: function () {
  18145. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18146. return null;
  18147. },
  18148. enumerable: true,
  18149. configurable: true
  18150. });
  18151. Scene.prototype.getLastFrameDuration = function () {
  18152. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  18153. return 0;
  18154. };
  18155. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  18156. get: function () {
  18157. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  18158. return null;
  18159. },
  18160. enumerable: true,
  18161. configurable: true
  18162. });
  18163. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  18164. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  18165. return 0;
  18166. };
  18167. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  18168. get: function () {
  18169. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18170. return null;
  18171. },
  18172. enumerable: true,
  18173. configurable: true
  18174. });
  18175. Scene.prototype.getActiveMeshes = function () {
  18176. return this._activeMeshes;
  18177. };
  18178. Scene.prototype.getRenderTargetsDuration = function () {
  18179. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  18180. return 0;
  18181. };
  18182. Scene.prototype.getRenderDuration = function () {
  18183. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  18184. return 0;
  18185. };
  18186. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  18187. get: function () {
  18188. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18189. return null;
  18190. },
  18191. enumerable: true,
  18192. configurable: true
  18193. });
  18194. Scene.prototype.getParticlesDuration = function () {
  18195. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  18196. return 0;
  18197. };
  18198. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  18199. get: function () {
  18200. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  18201. return null;
  18202. },
  18203. enumerable: true,
  18204. configurable: true
  18205. });
  18206. Scene.prototype.getSpritesDuration = function () {
  18207. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  18208. return 0;
  18209. };
  18210. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  18211. get: function () {
  18212. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  18213. return null;
  18214. },
  18215. enumerable: true,
  18216. configurable: true
  18217. });
  18218. Scene.prototype.getAnimationRatio = function () {
  18219. return this._animationRatio;
  18220. };
  18221. Scene.prototype.getRenderId = function () {
  18222. return this._renderId;
  18223. };
  18224. Scene.prototype.incrementRenderId = function () {
  18225. this._renderId++;
  18226. };
  18227. Scene.prototype._updatePointerPosition = function (evt) {
  18228. var canvasRect = this._engine.getRenderingCanvasClientRect();
  18229. if (!canvasRect) {
  18230. return;
  18231. }
  18232. this._pointerX = evt.clientX - canvasRect.left;
  18233. this._pointerY = evt.clientY - canvasRect.top;
  18234. this._unTranslatedPointerX = this._pointerX;
  18235. this._unTranslatedPointerY = this._pointerY;
  18236. };
  18237. Scene.prototype._createUbo = function () {
  18238. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18239. this._sceneUbo.addUniform("viewProjection", 16);
  18240. this._sceneUbo.addUniform("view", 16);
  18241. };
  18242. Scene.prototype._createAlternateUbo = function () {
  18243. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  18244. this._alternateSceneUbo.addUniform("viewProjection", 16);
  18245. this._alternateSceneUbo.addUniform("view", 16);
  18246. };
  18247. // Pointers handling
  18248. /**
  18249. * Use this method to simulate a pointer move on a mesh
  18250. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18251. */
  18252. Scene.prototype.simulatePointerMove = function (pickResult) {
  18253. var evt = new PointerEvent("pointermove");
  18254. return this._processPointerMove(pickResult, evt);
  18255. };
  18256. Scene.prototype._processPointerMove = function (pickResult, evt) {
  18257. var canvas = this._engine.getRenderingCanvas();
  18258. if (!canvas) {
  18259. return this;
  18260. }
  18261. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18262. this.setPointerOverSprite(null);
  18263. this.setPointerOverMesh(pickResult.pickedMesh);
  18264. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18265. if (this._pointerOverMesh.actionManager.hoverCursor) {
  18266. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  18267. }
  18268. else {
  18269. canvas.style.cursor = this.hoverCursor;
  18270. }
  18271. }
  18272. else {
  18273. canvas.style.cursor = this.defaultCursor;
  18274. }
  18275. }
  18276. else {
  18277. this.setPointerOverMesh(null);
  18278. // Sprites
  18279. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  18280. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18281. this.setPointerOverSprite(pickResult.pickedSprite);
  18282. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  18283. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  18284. }
  18285. else {
  18286. canvas.style.cursor = this.hoverCursor;
  18287. }
  18288. }
  18289. else {
  18290. this.setPointerOverSprite(null);
  18291. // Restore pointer
  18292. canvas.style.cursor = this.defaultCursor;
  18293. }
  18294. }
  18295. if (pickResult) {
  18296. if (this.onPointerMove) {
  18297. this.onPointerMove(evt, pickResult);
  18298. }
  18299. if (this.onPointerObservable.hasObservers()) {
  18300. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18301. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18302. this.onPointerObservable.notifyObservers(pi, type);
  18303. }
  18304. }
  18305. return this;
  18306. };
  18307. /**
  18308. * Use this method to simulate a pointer down on a mesh
  18309. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18310. */
  18311. Scene.prototype.simulatePointerDown = function (pickResult) {
  18312. var evt = new PointerEvent("pointerdown");
  18313. return this._processPointerDown(pickResult, evt);
  18314. };
  18315. Scene.prototype._processPointerDown = function (pickResult, evt) {
  18316. var _this = this;
  18317. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  18318. this._pickedDownMesh = pickResult.pickedMesh;
  18319. var actionManager = pickResult.pickedMesh.actionManager;
  18320. if (actionManager) {
  18321. if (actionManager.hasPickTriggers) {
  18322. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18323. switch (evt.button) {
  18324. case 0:
  18325. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18326. break;
  18327. case 1:
  18328. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18329. break;
  18330. case 2:
  18331. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18332. break;
  18333. }
  18334. }
  18335. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18336. window.setTimeout(function () {
  18337. 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);
  18338. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  18339. if (_this._totalPointersPressed !== 0 &&
  18340. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  18341. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  18342. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  18343. _this._startingPointerTime = 0;
  18344. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18345. }
  18346. }
  18347. }, Scene.LongPressDelay);
  18348. }
  18349. }
  18350. }
  18351. if (pickResult) {
  18352. if (this.onPointerDown) {
  18353. this.onPointerDown(evt, pickResult);
  18354. }
  18355. if (this.onPointerObservable.hasObservers()) {
  18356. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18357. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18358. this.onPointerObservable.notifyObservers(pi, type);
  18359. }
  18360. }
  18361. return this;
  18362. };
  18363. /**
  18364. * Use this method to simulate a pointer up on a mesh
  18365. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  18366. */
  18367. Scene.prototype.simulatePointerUp = function (pickResult) {
  18368. var evt = new PointerEvent("pointerup");
  18369. var clickInfo = new ClickInfo();
  18370. clickInfo.singleClick = true;
  18371. return this._processPointerUp(pickResult, evt, clickInfo);
  18372. };
  18373. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  18374. if (pickResult && pickResult && pickResult.pickedMesh) {
  18375. this._pickedUpMesh = pickResult.pickedMesh;
  18376. if (this._pickedDownMesh === this._pickedUpMesh) {
  18377. if (this.onPointerPick) {
  18378. this.onPointerPick(evt, pickResult);
  18379. }
  18380. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  18381. var type = BABYLON.PointerEventTypes.POINTERPICK;
  18382. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18383. this.onPointerObservable.notifyObservers(pi, type);
  18384. }
  18385. }
  18386. if (pickResult.pickedMesh.actionManager) {
  18387. if (clickInfo.ignore) {
  18388. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18389. }
  18390. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  18391. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18392. }
  18393. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18394. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18395. }
  18396. }
  18397. }
  18398. if (this._pickedDownMesh &&
  18399. this._pickedDownMesh.actionManager &&
  18400. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  18401. this._pickedDownMesh !== this._pickedUpMesh) {
  18402. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  18403. }
  18404. if (this.onPointerUp) {
  18405. this.onPointerUp(evt, pickResult);
  18406. }
  18407. if (this.onPointerObservable.hasObservers()) {
  18408. if (!clickInfo.ignore) {
  18409. if (!clickInfo.hasSwiped) {
  18410. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18411. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18412. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18413. this.onPointerObservable.notifyObservers(pi, type);
  18414. }
  18415. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18416. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18417. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18418. this.onPointerObservable.notifyObservers(pi, type);
  18419. }
  18420. }
  18421. }
  18422. else {
  18423. var type = BABYLON.PointerEventTypes.POINTERUP;
  18424. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  18425. this.onPointerObservable.notifyObservers(pi, type);
  18426. }
  18427. }
  18428. return this;
  18429. };
  18430. /**
  18431. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18432. * @param attachUp defines if you want to attach events to pointerup
  18433. * @param attachDown defines if you want to attach events to pointerdown
  18434. * @param attachMove defines if you want to attach events to pointermove
  18435. */
  18436. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18437. var _this = this;
  18438. if (attachUp === void 0) { attachUp = true; }
  18439. if (attachDown === void 0) { attachDown = true; }
  18440. if (attachMove === void 0) { attachMove = true; }
  18441. this._initActionManager = function (act, clickInfo) {
  18442. if (!_this._meshPickProceed) {
  18443. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18444. _this._currentPickResult = pickResult;
  18445. if (pickResult) {
  18446. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  18447. }
  18448. _this._meshPickProceed = true;
  18449. }
  18450. return act;
  18451. };
  18452. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  18453. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  18454. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  18455. btn !== _this._previousButtonPressed) {
  18456. _this._doubleClickOccured = false;
  18457. clickInfo.singleClick = true;
  18458. clickInfo.ignore = false;
  18459. cb(clickInfo, _this._currentPickResult);
  18460. }
  18461. };
  18462. this._initClickEvent = function (obs1, obs2, evt, cb) {
  18463. var clickInfo = new ClickInfo();
  18464. _this._currentPickResult = null;
  18465. var act = null;
  18466. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  18467. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  18468. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18469. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  18470. act = _this._initActionManager(act, clickInfo);
  18471. if (act)
  18472. checkPicking = act.hasPickTriggers;
  18473. }
  18474. if (checkPicking) {
  18475. var btn = evt.button;
  18476. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  18477. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  18478. if (!clickInfo.hasSwiped) {
  18479. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  18480. if (!checkSingleClickImmediately) {
  18481. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  18482. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18483. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18484. act = _this._initActionManager(act, clickInfo);
  18485. if (act)
  18486. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18487. }
  18488. }
  18489. if (checkSingleClickImmediately) {
  18490. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  18491. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  18492. btn !== _this._previousButtonPressed) {
  18493. clickInfo.singleClick = true;
  18494. cb(clickInfo, _this._currentPickResult);
  18495. }
  18496. }
  18497. else {
  18498. // wait that no double click has been raised during the double click delay
  18499. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18500. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  18501. }
  18502. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  18503. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  18504. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  18505. act = _this._initActionManager(act, clickInfo);
  18506. if (act)
  18507. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  18508. }
  18509. if (checkDoubleClick) {
  18510. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  18511. if (btn === _this._previousButtonPressed &&
  18512. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  18513. !_this._doubleClickOccured) {
  18514. // pointer has not moved for 2 clicks, it's a double click
  18515. if (!clickInfo.hasSwiped &&
  18516. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  18517. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  18518. _this._previousStartingPointerTime = 0;
  18519. _this._doubleClickOccured = true;
  18520. clickInfo.doubleClick = true;
  18521. clickInfo.ignore = false;
  18522. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  18523. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18524. }
  18525. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18526. cb(clickInfo, _this._currentPickResult);
  18527. }
  18528. else {
  18529. _this._doubleClickOccured = false;
  18530. _this._previousStartingPointerTime = _this._startingPointerTime;
  18531. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18532. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18533. _this._previousButtonPressed = btn;
  18534. _this._previousHasSwiped = clickInfo.hasSwiped;
  18535. if (Scene.ExclusiveDoubleClickMode) {
  18536. if (_this._previousDelayedSimpleClickTimeout) {
  18537. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  18538. }
  18539. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  18540. cb(clickInfo, _this._previousPickResult);
  18541. }
  18542. else {
  18543. cb(clickInfo, _this._currentPickResult);
  18544. }
  18545. }
  18546. }
  18547. else {
  18548. _this._doubleClickOccured = false;
  18549. _this._previousStartingPointerTime = _this._startingPointerTime;
  18550. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  18551. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  18552. _this._previousButtonPressed = btn;
  18553. _this._previousHasSwiped = clickInfo.hasSwiped;
  18554. }
  18555. }
  18556. }
  18557. }
  18558. clickInfo.ignore = true;
  18559. cb(clickInfo, _this._currentPickResult);
  18560. };
  18561. this._spritePredicate = function (sprite) {
  18562. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18563. };
  18564. this._onPointerMove = function (evt) {
  18565. _this._updatePointerPosition(evt);
  18566. // PreObservable support
  18567. if (_this.onPrePointerObservable.hasObservers()) {
  18568. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  18569. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18570. _this.onPrePointerObservable.notifyObservers(pi, type);
  18571. if (pi.skipOnPointerObservable) {
  18572. return;
  18573. }
  18574. }
  18575. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18576. return;
  18577. }
  18578. if (!_this.pointerMovePredicate) {
  18579. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  18580. }
  18581. // Meshes
  18582. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18583. _this._processPointerMove(pickResult, evt);
  18584. };
  18585. this._onPointerDown = function (evt) {
  18586. _this._totalPointersPressed++;
  18587. _this._pickedDownMesh = null;
  18588. _this._meshPickProceed = false;
  18589. _this._updatePointerPosition(evt);
  18590. if (_this.preventDefaultOnPointerDown && canvas) {
  18591. evt.preventDefault();
  18592. canvas.focus();
  18593. }
  18594. // PreObservable support
  18595. if (_this.onPrePointerObservable.hasObservers()) {
  18596. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  18597. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18598. _this.onPrePointerObservable.notifyObservers(pi, type);
  18599. if (pi.skipOnPointerObservable) {
  18600. return;
  18601. }
  18602. }
  18603. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18604. return;
  18605. }
  18606. _this._startingPointerPosition.x = _this._pointerX;
  18607. _this._startingPointerPosition.y = _this._pointerY;
  18608. _this._startingPointerTime = new Date().getTime();
  18609. if (!_this.pointerDownPredicate) {
  18610. _this.pointerDownPredicate = function (mesh) {
  18611. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18612. };
  18613. }
  18614. // Meshes
  18615. _this._pickedDownMesh = null;
  18616. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18617. _this._processPointerDown(pickResult, evt);
  18618. // Sprites
  18619. _this._pickedDownSprite = null;
  18620. if (_this.spriteManagers.length > 0) {
  18621. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18622. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  18623. if (pickResult.pickedSprite.actionManager) {
  18624. _this._pickedDownSprite = pickResult.pickedSprite;
  18625. switch (evt.button) {
  18626. case 0:
  18627. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18628. break;
  18629. case 1:
  18630. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18631. break;
  18632. case 2:
  18633. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18634. break;
  18635. }
  18636. if (pickResult.pickedSprite.actionManager) {
  18637. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18638. }
  18639. }
  18640. }
  18641. }
  18642. };
  18643. this._onPointerUp = function (evt) {
  18644. if (_this._totalPointersPressed === 0) {
  18645. return; // So we need to test it the pointer down was pressed before.
  18646. }
  18647. _this._totalPointersPressed--;
  18648. _this._pickedUpMesh = null;
  18649. _this._meshPickProceed = false;
  18650. _this._updatePointerPosition(evt);
  18651. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  18652. // PreObservable support
  18653. if (_this.onPrePointerObservable.hasObservers()) {
  18654. if (!clickInfo.ignore) {
  18655. if (!clickInfo.hasSwiped) {
  18656. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  18657. var type = BABYLON.PointerEventTypes.POINTERTAP;
  18658. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18659. _this.onPrePointerObservable.notifyObservers(pi, type);
  18660. if (pi.skipOnPointerObservable) {
  18661. return;
  18662. }
  18663. }
  18664. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  18665. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  18666. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18667. _this.onPrePointerObservable.notifyObservers(pi, type);
  18668. if (pi.skipOnPointerObservable) {
  18669. return;
  18670. }
  18671. }
  18672. }
  18673. }
  18674. else {
  18675. var type = BABYLON.PointerEventTypes.POINTERUP;
  18676. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18677. _this.onPrePointerObservable.notifyObservers(pi, type);
  18678. if (pi.skipOnPointerObservable) {
  18679. return;
  18680. }
  18681. }
  18682. }
  18683. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18684. return;
  18685. }
  18686. if (!_this.pointerUpPredicate) {
  18687. _this.pointerUpPredicate = function (mesh) {
  18688. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  18689. };
  18690. }
  18691. // Meshes
  18692. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  18693. _this._initActionManager(null, clickInfo);
  18694. }
  18695. if (!pickResult) {
  18696. pickResult = _this._currentPickResult;
  18697. }
  18698. _this._processPointerUp(pickResult, evt, clickInfo);
  18699. // Sprites
  18700. if (_this.spriteManagers.length > 0) {
  18701. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  18702. if (spritePickResult) {
  18703. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  18704. if (spritePickResult.pickedSprite.actionManager) {
  18705. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18706. if (spritePickResult.pickedSprite.actionManager) {
  18707. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  18708. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  18709. }
  18710. }
  18711. }
  18712. }
  18713. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  18714. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18715. }
  18716. }
  18717. }
  18718. _this._previousPickResult = _this._currentPickResult;
  18719. });
  18720. };
  18721. this._onKeyDown = function (evt) {
  18722. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  18723. if (_this.onPreKeyboardObservable.hasObservers()) {
  18724. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18725. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18726. if (pi.skipOnPointerObservable) {
  18727. return;
  18728. }
  18729. }
  18730. if (_this.onKeyboardObservable.hasObservers()) {
  18731. var pi = new BABYLON.KeyboardInfo(type, evt);
  18732. _this.onKeyboardObservable.notifyObservers(pi, type);
  18733. }
  18734. if (_this.actionManager) {
  18735. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18736. }
  18737. };
  18738. this._onKeyUp = function (evt) {
  18739. var type = BABYLON.KeyboardEventTypes.KEYUP;
  18740. if (_this.onPreKeyboardObservable.hasObservers()) {
  18741. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  18742. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  18743. if (pi.skipOnPointerObservable) {
  18744. return;
  18745. }
  18746. }
  18747. if (_this.onKeyboardObservable.hasObservers()) {
  18748. var pi = new BABYLON.KeyboardInfo(type, evt);
  18749. _this.onKeyboardObservable.notifyObservers(pi, type);
  18750. }
  18751. if (_this.actionManager) {
  18752. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18753. }
  18754. };
  18755. var engine = this.getEngine();
  18756. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  18757. if (!canvas) {
  18758. return;
  18759. }
  18760. canvas.addEventListener("keydown", _this._onKeyDown, false);
  18761. canvas.addEventListener("keyup", _this._onKeyUp, false);
  18762. });
  18763. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  18764. if (!canvas) {
  18765. return;
  18766. }
  18767. canvas.removeEventListener("keydown", _this._onKeyDown);
  18768. canvas.removeEventListener("keyup", _this._onKeyUp);
  18769. });
  18770. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18771. var canvas = this._engine.getRenderingCanvas();
  18772. if (!canvas) {
  18773. return;
  18774. }
  18775. if (attachMove) {
  18776. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18777. // Wheel
  18778. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18779. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18780. }
  18781. if (attachDown) {
  18782. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18783. }
  18784. if (attachUp) {
  18785. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18786. }
  18787. canvas.tabIndex = 1;
  18788. };
  18789. Scene.prototype.detachControl = function () {
  18790. var engine = this.getEngine();
  18791. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18792. var canvas = engine.getRenderingCanvas();
  18793. if (!canvas) {
  18794. return;
  18795. }
  18796. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18797. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18798. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18799. if (this._onCanvasBlurObserver) {
  18800. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  18801. }
  18802. if (this._onCanvasFocusObserver) {
  18803. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  18804. }
  18805. // Wheel
  18806. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18807. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18808. // Keyboard
  18809. canvas.removeEventListener("keydown", this._onKeyDown);
  18810. canvas.removeEventListener("keyup", this._onKeyUp);
  18811. // Observables
  18812. this.onKeyboardObservable.clear();
  18813. this.onPreKeyboardObservable.clear();
  18814. this.onPointerObservable.clear();
  18815. this.onPrePointerObservable.clear();
  18816. };
  18817. // Ready
  18818. Scene.prototype.isReady = function () {
  18819. if (this._isDisposed) {
  18820. return false;
  18821. }
  18822. if (this._pendingData.length > 0) {
  18823. return false;
  18824. }
  18825. var index;
  18826. // Geometries
  18827. for (index = 0; index < this._geometries.length; index++) {
  18828. var geometry = this._geometries[index];
  18829. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18830. return false;
  18831. }
  18832. }
  18833. // Meshes
  18834. for (index = 0; index < this.meshes.length; index++) {
  18835. var mesh = this.meshes[index];
  18836. if (!mesh.isEnabled()) {
  18837. continue;
  18838. }
  18839. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  18840. continue;
  18841. }
  18842. if (!mesh.isReady()) {
  18843. return false;
  18844. }
  18845. var mat = mesh.material;
  18846. if (mat) {
  18847. if (!mat.isReady(mesh)) {
  18848. return false;
  18849. }
  18850. }
  18851. }
  18852. return true;
  18853. };
  18854. Scene.prototype.resetCachedMaterial = function () {
  18855. this._cachedMaterial = null;
  18856. this._cachedEffect = null;
  18857. this._cachedVisibility = null;
  18858. };
  18859. Scene.prototype.registerBeforeRender = function (func) {
  18860. this.onBeforeRenderObservable.add(func);
  18861. };
  18862. Scene.prototype.unregisterBeforeRender = function (func) {
  18863. this.onBeforeRenderObservable.removeCallback(func);
  18864. };
  18865. Scene.prototype.registerAfterRender = function (func) {
  18866. this.onAfterRenderObservable.add(func);
  18867. };
  18868. Scene.prototype.unregisterAfterRender = function (func) {
  18869. this.onAfterRenderObservable.removeCallback(func);
  18870. };
  18871. Scene.prototype._addPendingData = function (data) {
  18872. this._pendingData.push(data);
  18873. };
  18874. Scene.prototype._removePendingData = function (data) {
  18875. var wasLoading = this.isLoading;
  18876. var index = this._pendingData.indexOf(data);
  18877. if (index !== -1) {
  18878. this._pendingData.splice(index, 1);
  18879. }
  18880. if (wasLoading && !this.isLoading) {
  18881. this.onDataLoadedObservable.notifyObservers(this);
  18882. }
  18883. };
  18884. Scene.prototype.getWaitingItemsCount = function () {
  18885. return this._pendingData.length;
  18886. };
  18887. Object.defineProperty(Scene.prototype, "isLoading", {
  18888. get: function () {
  18889. return this._pendingData.length > 0;
  18890. },
  18891. enumerable: true,
  18892. configurable: true
  18893. });
  18894. /**
  18895. * Registers a function to be executed when the scene is ready.
  18896. * @param {Function} func - the function to be executed.
  18897. */
  18898. Scene.prototype.executeWhenReady = function (func) {
  18899. var _this = this;
  18900. this.onReadyObservable.add(func);
  18901. if (this._executeWhenReadyTimeoutId !== -1) {
  18902. return;
  18903. }
  18904. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18905. _this._checkIsReady();
  18906. }, 150);
  18907. };
  18908. Scene.prototype._checkIsReady = function () {
  18909. var _this = this;
  18910. if (this.isReady()) {
  18911. this.onReadyObservable.notifyObservers(this);
  18912. this.onReadyObservable.clear();
  18913. this._executeWhenReadyTimeoutId = -1;
  18914. return;
  18915. }
  18916. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18917. _this._checkIsReady();
  18918. }, 150);
  18919. };
  18920. // Animations
  18921. /**
  18922. * Will start the animation sequence of a given target
  18923. * @param target - the target
  18924. * @param {number} from - from which frame should animation start
  18925. * @param {number} to - till which frame should animation run.
  18926. * @param {boolean} [loop] - should the animation loop
  18927. * @param {number} [speedRatio] - the speed in which to run the animation
  18928. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18929. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18930. * Returns {BABYLON.Animatable} the animatable object created for this animation
  18931. * See BABYLON.Animatable
  18932. */
  18933. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18934. if (speedRatio === void 0) { speedRatio = 1.0; }
  18935. if (from > to && speedRatio > 0) {
  18936. speedRatio *= -1;
  18937. }
  18938. this.stopAnimation(target);
  18939. if (!animatable) {
  18940. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18941. }
  18942. // Local animations
  18943. if (target.animations) {
  18944. animatable.appendAnimations(target, target.animations);
  18945. }
  18946. // Children animations
  18947. if (target.getAnimatables) {
  18948. var animatables = target.getAnimatables();
  18949. for (var index = 0; index < animatables.length; index++) {
  18950. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18951. }
  18952. }
  18953. animatable.reset();
  18954. return animatable;
  18955. };
  18956. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18957. if (speedRatio === undefined) {
  18958. speedRatio = 1.0;
  18959. }
  18960. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18961. return animatable;
  18962. };
  18963. Scene.prototype.getAnimatableByTarget = function (target) {
  18964. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18965. if (this._activeAnimatables[index].target === target) {
  18966. return this._activeAnimatables[index];
  18967. }
  18968. }
  18969. return null;
  18970. };
  18971. Object.defineProperty(Scene.prototype, "Animatables", {
  18972. get: function () {
  18973. return this._activeAnimatables;
  18974. },
  18975. enumerable: true,
  18976. configurable: true
  18977. });
  18978. /**
  18979. * Will stop the animation of the given target
  18980. * @param target - the target
  18981. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18982. * @see beginAnimation
  18983. */
  18984. Scene.prototype.stopAnimation = function (target, animationName) {
  18985. var animatable = this.getAnimatableByTarget(target);
  18986. if (animatable) {
  18987. animatable.stop(animationName);
  18988. }
  18989. };
  18990. Scene.prototype._animate = function () {
  18991. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18992. return;
  18993. }
  18994. // Getting time
  18995. var now = BABYLON.Tools.Now;
  18996. if (!this._animationTimeLast) {
  18997. if (this._pendingData.length > 0) {
  18998. return;
  18999. }
  19000. this._animationTimeLast = now;
  19001. }
  19002. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  19003. this._animationTime += deltaTime;
  19004. this._animationTimeLast = now;
  19005. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19006. this._activeAnimatables[index]._animate(this._animationTime);
  19007. }
  19008. };
  19009. // Matrix
  19010. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  19011. this._useAlternateCameraConfiguration = active;
  19012. };
  19013. Scene.prototype.getViewMatrix = function () {
  19014. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  19015. };
  19016. Scene.prototype.getProjectionMatrix = function () {
  19017. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  19018. };
  19019. Scene.prototype.getTransformMatrix = function () {
  19020. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  19021. };
  19022. Scene.prototype.setTransformMatrix = function (view, projection) {
  19023. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  19024. return;
  19025. }
  19026. this._viewUpdateFlag = view.updateFlag;
  19027. this._projectionUpdateFlag = projection.updateFlag;
  19028. this._viewMatrix = view;
  19029. this._projectionMatrix = projection;
  19030. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19031. // Update frustum
  19032. if (!this._frustumPlanes) {
  19033. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19034. }
  19035. else {
  19036. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19037. }
  19038. if (this.activeCamera && this.activeCamera._alternateCamera) {
  19039. var otherCamera = this.activeCamera._alternateCamera;
  19040. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  19041. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  19042. }
  19043. if (this._sceneUbo.useUbo) {
  19044. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  19045. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  19046. this._sceneUbo.update();
  19047. }
  19048. };
  19049. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  19050. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  19051. return;
  19052. }
  19053. this._alternateViewUpdateFlag = view.updateFlag;
  19054. this._alternateProjectionUpdateFlag = projection.updateFlag;
  19055. this._alternateViewMatrix = view;
  19056. this._alternateProjectionMatrix = projection;
  19057. if (!this._alternateTransformMatrix) {
  19058. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  19059. }
  19060. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  19061. if (!this._alternateSceneUbo) {
  19062. this._createAlternateUbo();
  19063. }
  19064. if (this._alternateSceneUbo.useUbo) {
  19065. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  19066. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  19067. this._alternateSceneUbo.update();
  19068. }
  19069. };
  19070. Scene.prototype.getSceneUniformBuffer = function () {
  19071. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  19072. };
  19073. // Methods
  19074. Scene.prototype.getUniqueId = function () {
  19075. var result = Scene._uniqueIdCounter;
  19076. Scene._uniqueIdCounter++;
  19077. return result;
  19078. };
  19079. Scene.prototype.addMesh = function (newMesh) {
  19080. this.meshes.push(newMesh);
  19081. //notify the collision coordinator
  19082. if (this.collisionCoordinator) {
  19083. this.collisionCoordinator.onMeshAdded(newMesh);
  19084. }
  19085. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  19086. };
  19087. Scene.prototype.removeMesh = function (toRemove) {
  19088. var index = this.meshes.indexOf(toRemove);
  19089. if (index !== -1) {
  19090. // Remove from the scene if mesh found
  19091. this.meshes.splice(index, 1);
  19092. }
  19093. //notify the collision coordinator
  19094. if (this.collisionCoordinator) {
  19095. this.collisionCoordinator.onMeshRemoved(toRemove);
  19096. }
  19097. this.onMeshRemovedObservable.notifyObservers(toRemove);
  19098. return index;
  19099. };
  19100. Scene.prototype.removeSkeleton = function (toRemove) {
  19101. var index = this.skeletons.indexOf(toRemove);
  19102. if (index !== -1) {
  19103. // Remove from the scene if found
  19104. this.skeletons.splice(index, 1);
  19105. }
  19106. return index;
  19107. };
  19108. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  19109. var index = this.morphTargetManagers.indexOf(toRemove);
  19110. if (index !== -1) {
  19111. // Remove from the scene if found
  19112. this.morphTargetManagers.splice(index, 1);
  19113. }
  19114. return index;
  19115. };
  19116. Scene.prototype.removeLight = function (toRemove) {
  19117. var index = this.lights.indexOf(toRemove);
  19118. if (index !== -1) {
  19119. // Remove from the scene if mesh found
  19120. this.lights.splice(index, 1);
  19121. this.sortLightsByPriority();
  19122. }
  19123. this.onLightRemovedObservable.notifyObservers(toRemove);
  19124. return index;
  19125. };
  19126. Scene.prototype.removeCamera = function (toRemove) {
  19127. var index = this.cameras.indexOf(toRemove);
  19128. if (index !== -1) {
  19129. // Remove from the scene if mesh found
  19130. this.cameras.splice(index, 1);
  19131. }
  19132. // Remove from activeCameras
  19133. var index2 = this.activeCameras.indexOf(toRemove);
  19134. if (index2 !== -1) {
  19135. // Remove from the scene if mesh found
  19136. this.activeCameras.splice(index2, 1);
  19137. }
  19138. // Reset the activeCamera
  19139. if (this.activeCamera === toRemove) {
  19140. if (this.cameras.length > 0) {
  19141. this.activeCamera = this.cameras[0];
  19142. }
  19143. else {
  19144. this.activeCamera = null;
  19145. }
  19146. }
  19147. this.onCameraRemovedObservable.notifyObservers(toRemove);
  19148. return index;
  19149. };
  19150. Scene.prototype.addLight = function (newLight) {
  19151. this.lights.push(newLight);
  19152. this.sortLightsByPriority();
  19153. this.onNewLightAddedObservable.notifyObservers(newLight);
  19154. };
  19155. Scene.prototype.sortLightsByPriority = function () {
  19156. if (this.requireLightSorting) {
  19157. this.lights.sort(BABYLON.Light.compareLightsPriority);
  19158. }
  19159. };
  19160. Scene.prototype.addCamera = function (newCamera) {
  19161. this.cameras.push(newCamera);
  19162. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  19163. };
  19164. /**
  19165. * Switch active camera
  19166. * @param {Camera} newCamera - new active camera
  19167. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  19168. */
  19169. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  19170. if (attachControl === void 0) { attachControl = true; }
  19171. var canvas = this._engine.getRenderingCanvas();
  19172. if (!canvas) {
  19173. return;
  19174. }
  19175. if (this.activeCamera) {
  19176. this.activeCamera.detachControl(canvas);
  19177. }
  19178. this.activeCamera = newCamera;
  19179. if (attachControl) {
  19180. newCamera.attachControl(canvas);
  19181. }
  19182. };
  19183. /**
  19184. * sets the active camera of the scene using its ID
  19185. * @param {string} id - the camera's ID
  19186. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19187. * @see activeCamera
  19188. */
  19189. Scene.prototype.setActiveCameraByID = function (id) {
  19190. var camera = this.getCameraByID(id);
  19191. if (camera) {
  19192. this.activeCamera = camera;
  19193. return camera;
  19194. }
  19195. return null;
  19196. };
  19197. /**
  19198. * sets the active camera of the scene using its name
  19199. * @param {string} name - the camera's name
  19200. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  19201. * @see activeCamera
  19202. */
  19203. Scene.prototype.setActiveCameraByName = function (name) {
  19204. var camera = this.getCameraByName(name);
  19205. if (camera) {
  19206. this.activeCamera = camera;
  19207. return camera;
  19208. }
  19209. return null;
  19210. };
  19211. /**
  19212. * get a material using its id
  19213. * @param {string} the material's ID
  19214. * @return {BABYLON.Material|null} the material or null if none found.
  19215. */
  19216. Scene.prototype.getMaterialByID = function (id) {
  19217. for (var index = 0; index < this.materials.length; index++) {
  19218. if (this.materials[index].id === id) {
  19219. return this.materials[index];
  19220. }
  19221. }
  19222. return null;
  19223. };
  19224. /**
  19225. * get a material using its name
  19226. * @param {string} the material's name
  19227. * @return {BABYLON.Material|null} the material or null if none found.
  19228. */
  19229. Scene.prototype.getMaterialByName = function (name) {
  19230. for (var index = 0; index < this.materials.length; index++) {
  19231. if (this.materials[index].name === name) {
  19232. return this.materials[index];
  19233. }
  19234. }
  19235. return null;
  19236. };
  19237. Scene.prototype.getLensFlareSystemByName = function (name) {
  19238. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19239. if (this.lensFlareSystems[index].name === name) {
  19240. return this.lensFlareSystems[index];
  19241. }
  19242. }
  19243. return null;
  19244. };
  19245. Scene.prototype.getLensFlareSystemByID = function (id) {
  19246. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  19247. if (this.lensFlareSystems[index].id === id) {
  19248. return this.lensFlareSystems[index];
  19249. }
  19250. }
  19251. return null;
  19252. };
  19253. Scene.prototype.getCameraByID = function (id) {
  19254. for (var index = 0; index < this.cameras.length; index++) {
  19255. if (this.cameras[index].id === id) {
  19256. return this.cameras[index];
  19257. }
  19258. }
  19259. return null;
  19260. };
  19261. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  19262. for (var index = 0; index < this.cameras.length; index++) {
  19263. if (this.cameras[index].uniqueId === uniqueId) {
  19264. return this.cameras[index];
  19265. }
  19266. }
  19267. return null;
  19268. };
  19269. /**
  19270. * get a camera using its name
  19271. * @param {string} the camera's name
  19272. * @return {BABYLON.Camera|null} the camera or null if none found.
  19273. */
  19274. Scene.prototype.getCameraByName = function (name) {
  19275. for (var index = 0; index < this.cameras.length; index++) {
  19276. if (this.cameras[index].name === name) {
  19277. return this.cameras[index];
  19278. }
  19279. }
  19280. return null;
  19281. };
  19282. /**
  19283. * get a bone using its id
  19284. * @param {string} the bone's id
  19285. * @return {BABYLON.Bone|null} the bone or null if not found
  19286. */
  19287. Scene.prototype.getBoneByID = function (id) {
  19288. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19289. var skeleton = this.skeletons[skeletonIndex];
  19290. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19291. if (skeleton.bones[boneIndex].id === id) {
  19292. return skeleton.bones[boneIndex];
  19293. }
  19294. }
  19295. }
  19296. return null;
  19297. };
  19298. /**
  19299. * get a bone using its id
  19300. * @param {string} the bone's name
  19301. * @return {BABYLON.Bone|null} the bone or null if not found
  19302. */
  19303. Scene.prototype.getBoneByName = function (name) {
  19304. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  19305. var skeleton = this.skeletons[skeletonIndex];
  19306. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  19307. if (skeleton.bones[boneIndex].name === name) {
  19308. return skeleton.bones[boneIndex];
  19309. }
  19310. }
  19311. }
  19312. return null;
  19313. };
  19314. /**
  19315. * get a light node using its name
  19316. * @param {string} the light's name
  19317. * @return {BABYLON.Light|null} the light or null if none found.
  19318. */
  19319. Scene.prototype.getLightByName = function (name) {
  19320. for (var index = 0; index < this.lights.length; index++) {
  19321. if (this.lights[index].name === name) {
  19322. return this.lights[index];
  19323. }
  19324. }
  19325. return null;
  19326. };
  19327. /**
  19328. * get a light node using its ID
  19329. * @param {string} the light's id
  19330. * @return {BABYLON.Light|null} the light or null if none found.
  19331. */
  19332. Scene.prototype.getLightByID = function (id) {
  19333. for (var index = 0; index < this.lights.length; index++) {
  19334. if (this.lights[index].id === id) {
  19335. return this.lights[index];
  19336. }
  19337. }
  19338. return null;
  19339. };
  19340. /**
  19341. * get a light node using its scene-generated unique ID
  19342. * @param {number} the light's unique id
  19343. * @return {BABYLON.Light|null} the light or null if none found.
  19344. */
  19345. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  19346. for (var index = 0; index < this.lights.length; index++) {
  19347. if (this.lights[index].uniqueId === uniqueId) {
  19348. return this.lights[index];
  19349. }
  19350. }
  19351. return null;
  19352. };
  19353. /**
  19354. * get a particle system by id
  19355. * @param id {number} the particle system id
  19356. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  19357. */
  19358. Scene.prototype.getParticleSystemByID = function (id) {
  19359. for (var index = 0; index < this.particleSystems.length; index++) {
  19360. if (this.particleSystems[index].id === id) {
  19361. return this.particleSystems[index];
  19362. }
  19363. }
  19364. return null;
  19365. };
  19366. /**
  19367. * get a geometry using its ID
  19368. * @param {string} the geometry's id
  19369. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  19370. */
  19371. Scene.prototype.getGeometryByID = function (id) {
  19372. for (var index = 0; index < this._geometries.length; index++) {
  19373. if (this._geometries[index].id === id) {
  19374. return this._geometries[index];
  19375. }
  19376. }
  19377. return null;
  19378. };
  19379. /**
  19380. * add a new geometry to this scene.
  19381. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  19382. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  19383. * @return {boolean} was the geometry added or not
  19384. */
  19385. Scene.prototype.pushGeometry = function (geometry, force) {
  19386. if (!force && this.getGeometryByID(geometry.id)) {
  19387. return false;
  19388. }
  19389. this._geometries.push(geometry);
  19390. //notify the collision coordinator
  19391. if (this.collisionCoordinator) {
  19392. this.collisionCoordinator.onGeometryAdded(geometry);
  19393. }
  19394. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  19395. return true;
  19396. };
  19397. /**
  19398. * Removes an existing geometry
  19399. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  19400. * @return {boolean} was the geometry removed or not
  19401. */
  19402. Scene.prototype.removeGeometry = function (geometry) {
  19403. var index = this._geometries.indexOf(geometry);
  19404. if (index > -1) {
  19405. this._geometries.splice(index, 1);
  19406. //notify the collision coordinator
  19407. if (this.collisionCoordinator) {
  19408. this.collisionCoordinator.onGeometryDeleted(geometry);
  19409. }
  19410. this.onGeometryRemovedObservable.notifyObservers(geometry);
  19411. return true;
  19412. }
  19413. return false;
  19414. };
  19415. Scene.prototype.getGeometries = function () {
  19416. return this._geometries;
  19417. };
  19418. /**
  19419. * Get the first added mesh found of a given ID
  19420. * @param {string} id - the id to search for
  19421. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19422. */
  19423. Scene.prototype.getMeshByID = function (id) {
  19424. for (var index = 0; index < this.meshes.length; index++) {
  19425. if (this.meshes[index].id === id) {
  19426. return this.meshes[index];
  19427. }
  19428. }
  19429. return null;
  19430. };
  19431. Scene.prototype.getMeshesByID = function (id) {
  19432. return this.meshes.filter(function (m) {
  19433. return m.id === id;
  19434. });
  19435. };
  19436. /**
  19437. * Get a mesh with its auto-generated unique id
  19438. * @param {number} uniqueId - the unique id to search for
  19439. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19440. */
  19441. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  19442. for (var index = 0; index < this.meshes.length; index++) {
  19443. if (this.meshes[index].uniqueId === uniqueId) {
  19444. return this.meshes[index];
  19445. }
  19446. }
  19447. return null;
  19448. };
  19449. /**
  19450. * Get a the last added mesh found of a given ID
  19451. * @param {string} id - the id to search for
  19452. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  19453. */
  19454. Scene.prototype.getLastMeshByID = function (id) {
  19455. for (var index = this.meshes.length - 1; index >= 0; index--) {
  19456. if (this.meshes[index].id === id) {
  19457. return this.meshes[index];
  19458. }
  19459. }
  19460. return null;
  19461. };
  19462. /**
  19463. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  19464. * @param {string} id - the id to search for
  19465. * @return {BABYLON.Node|null} the node found or null if not found at all.
  19466. */
  19467. Scene.prototype.getLastEntryByID = function (id) {
  19468. var index;
  19469. for (index = this.meshes.length - 1; index >= 0; index--) {
  19470. if (this.meshes[index].id === id) {
  19471. return this.meshes[index];
  19472. }
  19473. }
  19474. for (index = this.cameras.length - 1; index >= 0; index--) {
  19475. if (this.cameras[index].id === id) {
  19476. return this.cameras[index];
  19477. }
  19478. }
  19479. for (index = this.lights.length - 1; index >= 0; index--) {
  19480. if (this.lights[index].id === id) {
  19481. return this.lights[index];
  19482. }
  19483. }
  19484. return null;
  19485. };
  19486. Scene.prototype.getNodeByID = function (id) {
  19487. var mesh = this.getMeshByID(id);
  19488. if (mesh) {
  19489. return mesh;
  19490. }
  19491. var light = this.getLightByID(id);
  19492. if (light) {
  19493. return light;
  19494. }
  19495. var camera = this.getCameraByID(id);
  19496. if (camera) {
  19497. return camera;
  19498. }
  19499. var bone = this.getBoneByID(id);
  19500. return bone;
  19501. };
  19502. Scene.prototype.getNodeByName = function (name) {
  19503. var mesh = this.getMeshByName(name);
  19504. if (mesh) {
  19505. return mesh;
  19506. }
  19507. var light = this.getLightByName(name);
  19508. if (light) {
  19509. return light;
  19510. }
  19511. var camera = this.getCameraByName(name);
  19512. if (camera) {
  19513. return camera;
  19514. }
  19515. var bone = this.getBoneByName(name);
  19516. return bone;
  19517. };
  19518. Scene.prototype.getMeshByName = function (name) {
  19519. for (var index = 0; index < this.meshes.length; index++) {
  19520. if (this.meshes[index].name === name) {
  19521. return this.meshes[index];
  19522. }
  19523. }
  19524. return null;
  19525. };
  19526. Scene.prototype.getSoundByName = function (name) {
  19527. var index;
  19528. if (BABYLON.AudioEngine) {
  19529. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  19530. if (this.mainSoundTrack.soundCollection[index].name === name) {
  19531. return this.mainSoundTrack.soundCollection[index];
  19532. }
  19533. }
  19534. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  19535. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  19536. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  19537. return this.soundTracks[sdIndex].soundCollection[index];
  19538. }
  19539. }
  19540. }
  19541. }
  19542. return null;
  19543. };
  19544. Scene.prototype.getLastSkeletonByID = function (id) {
  19545. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  19546. if (this.skeletons[index].id === id) {
  19547. return this.skeletons[index];
  19548. }
  19549. }
  19550. return null;
  19551. };
  19552. Scene.prototype.getSkeletonById = function (id) {
  19553. for (var index = 0; index < this.skeletons.length; index++) {
  19554. if (this.skeletons[index].id === id) {
  19555. return this.skeletons[index];
  19556. }
  19557. }
  19558. return null;
  19559. };
  19560. Scene.prototype.getSkeletonByName = function (name) {
  19561. for (var index = 0; index < this.skeletons.length; index++) {
  19562. if (this.skeletons[index].name === name) {
  19563. return this.skeletons[index];
  19564. }
  19565. }
  19566. return null;
  19567. };
  19568. Scene.prototype.getMorphTargetManagerById = function (id) {
  19569. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  19570. if (this.morphTargetManagers[index].uniqueId === id) {
  19571. return this.morphTargetManagers[index];
  19572. }
  19573. }
  19574. return null;
  19575. };
  19576. Scene.prototype.isActiveMesh = function (mesh) {
  19577. return (this._activeMeshes.indexOf(mesh) !== -1);
  19578. };
  19579. /**
  19580. * Return a the first highlight layer of the scene with a given name.
  19581. * @param name The name of the highlight layer to look for.
  19582. * @return The highlight layer if found otherwise null.
  19583. */
  19584. Scene.prototype.getHighlightLayerByName = function (name) {
  19585. for (var index = 0; index < this.highlightLayers.length; index++) {
  19586. if (this.highlightLayers[index].name === name) {
  19587. return this.highlightLayers[index];
  19588. }
  19589. }
  19590. return null;
  19591. };
  19592. Object.defineProperty(Scene.prototype, "uid", {
  19593. /**
  19594. * Return a unique id as a string which can serve as an identifier for the scene
  19595. */
  19596. get: function () {
  19597. if (!this._uid) {
  19598. this._uid = BABYLON.Tools.RandomId();
  19599. }
  19600. return this._uid;
  19601. },
  19602. enumerable: true,
  19603. configurable: true
  19604. });
  19605. /**
  19606. * Add an externaly attached data from its key.
  19607. * This method call will fail and return false, if such key already exists.
  19608. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  19609. * @param key the unique key that identifies the data
  19610. * @param data the data object to associate to the key for this Engine instance
  19611. * @return true if no such key were already present and the data was added successfully, false otherwise
  19612. */
  19613. Scene.prototype.addExternalData = function (key, data) {
  19614. if (!this._externalData) {
  19615. this._externalData = new BABYLON.StringDictionary();
  19616. }
  19617. return this._externalData.add(key, data);
  19618. };
  19619. /**
  19620. * Get an externaly attached data from its key
  19621. * @param key the unique key that identifies the data
  19622. * @return the associated data, if present (can be null), or undefined if not present
  19623. */
  19624. Scene.prototype.getExternalData = function (key) {
  19625. if (!this._externalData) {
  19626. return null;
  19627. }
  19628. return this._externalData.get(key);
  19629. };
  19630. /**
  19631. * Get an externaly attached data from its key, create it using a factory if it's not already present
  19632. * @param key the unique key that identifies the data
  19633. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  19634. * @return the associated data, can be null if the factory returned null.
  19635. */
  19636. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  19637. if (!this._externalData) {
  19638. this._externalData = new BABYLON.StringDictionary();
  19639. }
  19640. return this._externalData.getOrAddWithFactory(key, factory);
  19641. };
  19642. /**
  19643. * Remove an externaly attached data from the Engine instance
  19644. * @param key the unique key that identifies the data
  19645. * @return true if the data was successfully removed, false if it doesn't exist
  19646. */
  19647. Scene.prototype.removeExternalData = function (key) {
  19648. return this._externalData.remove(key);
  19649. };
  19650. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  19651. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  19652. var material = subMesh.getMaterial();
  19653. if (mesh.showSubMeshesBoundingBox) {
  19654. var boundingInfo = subMesh.getBoundingInfo();
  19655. if (boundingInfo) {
  19656. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19657. }
  19658. }
  19659. if (material) {
  19660. // Render targets
  19661. if (material.getRenderTargetTextures) {
  19662. if (this._processedMaterials.indexOf(material) === -1) {
  19663. this._processedMaterials.push(material);
  19664. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19665. }
  19666. }
  19667. // Dispatch
  19668. this._activeIndices.addCount(subMesh.indexCount, false);
  19669. this._renderingManager.dispatch(subMesh);
  19670. }
  19671. }
  19672. };
  19673. Scene.prototype._isInIntermediateRendering = function () {
  19674. return this._intermediateRendering;
  19675. };
  19676. /**
  19677. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  19678. */
  19679. Scene.prototype.freezeActiveMeshes = function () {
  19680. this._evaluateActiveMeshes();
  19681. this._activeMeshesFrozen = true;
  19682. return this;
  19683. };
  19684. /**
  19685. * Use this function to restart evaluating active meshes on every frame
  19686. */
  19687. Scene.prototype.unfreezeActiveMeshes = function () {
  19688. this._activeMeshesFrozen = false;
  19689. return this;
  19690. };
  19691. Scene.prototype._evaluateActiveMeshes = function () {
  19692. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  19693. return;
  19694. }
  19695. if (!this.activeCamera) {
  19696. return;
  19697. }
  19698. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  19699. this.activeCamera._activeMeshes.reset();
  19700. this._activeMeshes.reset();
  19701. this._renderingManager.reset();
  19702. this._processedMaterials.reset();
  19703. this._activeParticleSystems.reset();
  19704. this._activeSkeletons.reset();
  19705. this._softwareSkinnedMeshes.reset();
  19706. if (this._boundingBoxRenderer) {
  19707. this._boundingBoxRenderer.reset();
  19708. }
  19709. // Meshes
  19710. var meshes;
  19711. var len;
  19712. if (this._selectionOctree) {
  19713. var selection = this._selectionOctree.select(this._frustumPlanes);
  19714. meshes = selection.data;
  19715. len = selection.length;
  19716. }
  19717. else {
  19718. len = this.meshes.length;
  19719. meshes = this.meshes;
  19720. }
  19721. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19722. var mesh = meshes[meshIndex];
  19723. if (mesh.isBlocked) {
  19724. continue;
  19725. }
  19726. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19727. if (!mesh.isReady() || !mesh.isEnabled()) {
  19728. continue;
  19729. }
  19730. mesh.computeWorldMatrix();
  19731. // Intersections
  19732. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19733. this._meshesForIntersections.pushNoDuplicate(mesh);
  19734. }
  19735. // Switch to current LOD
  19736. var meshLOD = mesh.getLOD(this.activeCamera);
  19737. if (!meshLOD) {
  19738. continue;
  19739. }
  19740. mesh._preActivate();
  19741. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19742. this._activeMeshes.push(mesh);
  19743. this.activeCamera._activeMeshes.push(mesh);
  19744. mesh._activate(this._renderId);
  19745. if (meshLOD !== mesh) {
  19746. meshLOD._activate(this._renderId);
  19747. }
  19748. this._activeMesh(mesh, meshLOD);
  19749. }
  19750. }
  19751. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  19752. // Particle systems
  19753. if (this.particlesEnabled) {
  19754. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  19755. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19756. var particleSystem = this.particleSystems[particleIndex];
  19757. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  19758. continue;
  19759. }
  19760. var emitter = particleSystem.emitter;
  19761. if (!emitter.position || emitter.isEnabled()) {
  19762. this._activeParticleSystems.push(particleSystem);
  19763. particleSystem.animate();
  19764. this._renderingManager.dispatchParticles(particleSystem);
  19765. }
  19766. }
  19767. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  19768. }
  19769. };
  19770. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19771. if (mesh.skeleton && this.skeletonsEnabled) {
  19772. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19773. mesh.skeleton.prepare();
  19774. }
  19775. if (!mesh.computeBonesUsingShaders) {
  19776. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19777. }
  19778. }
  19779. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19780. var boundingInfo = sourceMesh.getBoundingInfo();
  19781. if (boundingInfo) {
  19782. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  19783. }
  19784. }
  19785. if (mesh && mesh.subMeshes) {
  19786. // Submeshes Octrees
  19787. var len;
  19788. var subMeshes;
  19789. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19790. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19791. len = intersections.length;
  19792. subMeshes = intersections.data;
  19793. }
  19794. else {
  19795. subMeshes = mesh.subMeshes;
  19796. len = subMeshes.length;
  19797. }
  19798. for (var subIndex = 0; subIndex < len; subIndex++) {
  19799. var subMesh = subMeshes[subIndex];
  19800. this._evaluateSubMesh(subMesh, mesh);
  19801. }
  19802. }
  19803. };
  19804. Scene.prototype.updateTransformMatrix = function (force) {
  19805. if (!this.activeCamera) {
  19806. return;
  19807. }
  19808. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19809. };
  19810. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  19811. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  19812. };
  19813. Scene.prototype._renderForCamera = function (camera) {
  19814. if (camera && camera._skipRendering) {
  19815. return;
  19816. }
  19817. var engine = this._engine;
  19818. this.activeCamera = camera;
  19819. if (!this.activeCamera)
  19820. throw new Error("Active camera not set");
  19821. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19822. // Viewport
  19823. engine.setViewport(this.activeCamera.viewport);
  19824. // Camera
  19825. this.resetCachedMaterial();
  19826. this._renderId++;
  19827. this.activeCamera.update();
  19828. this.updateTransformMatrix();
  19829. if (camera._alternateCamera) {
  19830. this.updateAlternateTransformMatrix(camera._alternateCamera);
  19831. this._alternateRendering = true;
  19832. }
  19833. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19834. // Meshes
  19835. this._evaluateActiveMeshes();
  19836. // Software skinning
  19837. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19838. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19839. mesh.applySkeleton(mesh.skeleton);
  19840. }
  19841. // Render targets
  19842. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  19843. var needsRestoreFrameBuffer = false;
  19844. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  19845. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  19846. }
  19847. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19848. this._intermediateRendering = true;
  19849. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19850. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19851. var renderTarget = this._renderTargets.data[renderIndex];
  19852. if (renderTarget._shouldRender()) {
  19853. this._renderId++;
  19854. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19855. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19856. }
  19857. }
  19858. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19859. this._intermediateRendering = false;
  19860. this._renderId++;
  19861. needsRestoreFrameBuffer = true; // Restore back buffer
  19862. }
  19863. // Render HighlightLayer Texture
  19864. var stencilState = this._engine.getStencilBuffer();
  19865. var renderhighlights = false;
  19866. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19867. this._intermediateRendering = true;
  19868. for (var i = 0; i < this.highlightLayers.length; i++) {
  19869. var highlightLayer = this.highlightLayers[i];
  19870. if (highlightLayer.shouldRender() &&
  19871. (!highlightLayer.camera ||
  19872. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19873. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19874. renderhighlights = true;
  19875. var renderTarget = highlightLayer._mainTexture;
  19876. if (renderTarget._shouldRender()) {
  19877. this._renderId++;
  19878. renderTarget.render(false, false);
  19879. needsRestoreFrameBuffer = true;
  19880. }
  19881. }
  19882. }
  19883. this._intermediateRendering = false;
  19884. this._renderId++;
  19885. }
  19886. if (needsRestoreFrameBuffer) {
  19887. engine.restoreDefaultFramebuffer(); // Restore back buffer
  19888. }
  19889. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  19890. // Prepare Frame
  19891. this.postProcessManager._prepareFrame();
  19892. // Backgrounds
  19893. var layerIndex;
  19894. var layer;
  19895. if (this.layers.length) {
  19896. engine.setDepthBuffer(false);
  19897. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19898. layer = this.layers[layerIndex];
  19899. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19900. layer.render();
  19901. }
  19902. }
  19903. engine.setDepthBuffer(true);
  19904. }
  19905. // Activate HighlightLayer stencil
  19906. if (renderhighlights) {
  19907. this._engine.setStencilBuffer(true);
  19908. }
  19909. // Render
  19910. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  19911. this._renderingManager.render(null, null, true, true);
  19912. this.onAfterDrawPhaseObservable.notifyObservers(this);
  19913. // Restore HighlightLayer stencil
  19914. if (renderhighlights) {
  19915. this._engine.setStencilBuffer(stencilState);
  19916. }
  19917. // Bounding boxes
  19918. if (this._boundingBoxRenderer) {
  19919. this._boundingBoxRenderer.render();
  19920. }
  19921. // Lens flares
  19922. if (this.lensFlaresEnabled) {
  19923. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19924. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19925. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19926. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19927. lensFlareSystem.render();
  19928. }
  19929. }
  19930. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19931. }
  19932. // Foregrounds
  19933. if (this.layers.length) {
  19934. engine.setDepthBuffer(false);
  19935. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19936. layer = this.layers[layerIndex];
  19937. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  19938. layer.render();
  19939. }
  19940. }
  19941. engine.setDepthBuffer(true);
  19942. }
  19943. // Highlight Layer
  19944. if (renderhighlights) {
  19945. engine.setDepthBuffer(false);
  19946. for (var i = 0; i < this.highlightLayers.length; i++) {
  19947. if (this.highlightLayers[i].shouldRender()) {
  19948. this.highlightLayers[i].render();
  19949. }
  19950. }
  19951. engine.setDepthBuffer(true);
  19952. }
  19953. // Finalize frame
  19954. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19955. // Reset some special arrays
  19956. this._renderTargets.reset();
  19957. this._alternateRendering = false;
  19958. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19959. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19960. };
  19961. Scene.prototype._processSubCameras = function (camera) {
  19962. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19963. this._renderForCamera(camera);
  19964. return;
  19965. }
  19966. // Update camera
  19967. if (this.activeCamera) {
  19968. this.activeCamera.update();
  19969. }
  19970. // rig cameras
  19971. for (var index = 0; index < camera._rigCameras.length; index++) {
  19972. this._renderForCamera(camera._rigCameras[index]);
  19973. }
  19974. this.activeCamera = camera;
  19975. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19976. };
  19977. Scene.prototype._checkIntersections = function () {
  19978. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19979. var sourceMesh = this._meshesForIntersections.data[index];
  19980. if (!sourceMesh.actionManager) {
  19981. continue;
  19982. }
  19983. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19984. var action = sourceMesh.actionManager.actions[actionIndex];
  19985. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19986. var parameters = action.getTriggerParameter();
  19987. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19988. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19989. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19990. if (areIntersecting && currentIntersectionInProgress === -1) {
  19991. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19992. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  19993. sourceMesh._intersectionsInProgress.push(otherMesh);
  19994. }
  19995. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19996. sourceMesh._intersectionsInProgress.push(otherMesh);
  19997. }
  19998. }
  19999. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  20000. //They intersected, and now they don't.
  20001. //is this trigger an exit trigger? execute an event.
  20002. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20003. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  20004. }
  20005. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  20006. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  20007. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  20008. }
  20009. }
  20010. }
  20011. }
  20012. }
  20013. };
  20014. Scene.prototype.render = function () {
  20015. if (this.isDisposed) {
  20016. return;
  20017. }
  20018. this._activeParticles.fetchNewFrame();
  20019. this._totalVertices.fetchNewFrame();
  20020. this._activeIndices.fetchNewFrame();
  20021. this._activeBones.fetchNewFrame();
  20022. this._meshesForIntersections.reset();
  20023. this.resetCachedMaterial();
  20024. this.onBeforeAnimationsObservable.notifyObservers(this);
  20025. // Actions
  20026. if (this.actionManager) {
  20027. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  20028. }
  20029. //Simplification Queue
  20030. if (this.simplificationQueue && !this.simplificationQueue.running) {
  20031. this.simplificationQueue.executeNext();
  20032. }
  20033. if (this._engine.isDeterministicLockStep()) {
  20034. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  20035. var defaultTimeStep = (60.0 / 1000.0);
  20036. if (this._physicsEngine) {
  20037. defaultTimeStep = this._physicsEngine.getTimeStep();
  20038. }
  20039. var maxSubSteps = this._engine.getLockstepMaxSteps();
  20040. this._timeAccumulator += deltaTime;
  20041. // compute the amount of fixed steps we should have taken since the last step
  20042. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  20043. internalSteps = Math.min(internalSteps, maxSubSteps);
  20044. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  20045. this.onBeforeStepObservable.notifyObservers(this);
  20046. // Animations
  20047. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  20048. this._animate();
  20049. this.onAfterAnimationsObservable.notifyObservers(this);
  20050. // Physics
  20051. if (this._physicsEngine) {
  20052. this.onBeforePhysicsObservable.notifyObservers(this);
  20053. this._physicsEngine._step(defaultTimeStep);
  20054. this.onAfterPhysicsObservable.notifyObservers(this);
  20055. }
  20056. this._timeAccumulator -= defaultTimeStep;
  20057. this.onAfterStepObservable.notifyObservers(this);
  20058. this._currentStepId++;
  20059. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  20060. this._evaluateActiveMeshes();
  20061. }
  20062. }
  20063. }
  20064. else {
  20065. // Animations
  20066. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  20067. this._animationRatio = deltaTime * (60.0 / 1000.0);
  20068. this._animate();
  20069. this.onAfterAnimationsObservable.notifyObservers(this);
  20070. // Physics
  20071. if (this._physicsEngine) {
  20072. this.onBeforePhysicsObservable.notifyObservers(this);
  20073. this._physicsEngine._step(deltaTime / 1000.0);
  20074. this.onAfterPhysicsObservable.notifyObservers(this);
  20075. }
  20076. }
  20077. // Before render
  20078. this.onBeforeRenderObservable.notifyObservers(this);
  20079. // Customs render targets
  20080. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20081. var engine = this.getEngine();
  20082. var currentActiveCamera = this.activeCamera;
  20083. if (this.renderTargetsEnabled) {
  20084. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20085. this._intermediateRendering = true;
  20086. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  20087. var renderTarget = this.customRenderTargets[customIndex];
  20088. if (renderTarget._shouldRender()) {
  20089. this._renderId++;
  20090. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  20091. if (!this.activeCamera)
  20092. throw new Error("Active camera not set");
  20093. // Viewport
  20094. engine.setViewport(this.activeCamera.viewport);
  20095. // Camera
  20096. this.updateTransformMatrix();
  20097. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  20098. }
  20099. }
  20100. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  20101. this._intermediateRendering = false;
  20102. this._renderId++;
  20103. }
  20104. // Restore back buffer
  20105. if (this.customRenderTargets.length > 0) {
  20106. engine.restoreDefaultFramebuffer();
  20107. }
  20108. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20109. this.activeCamera = currentActiveCamera;
  20110. // Procedural textures
  20111. if (this.proceduralTexturesEnabled) {
  20112. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20113. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  20114. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  20115. if (proceduralTexture._shouldRender()) {
  20116. proceduralTexture.render();
  20117. }
  20118. }
  20119. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  20120. }
  20121. // Clear
  20122. if (this.autoClearDepthAndStencil || this.autoClear) {
  20123. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  20124. }
  20125. // Shadows
  20126. if (this.shadowsEnabled) {
  20127. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  20128. var light = this.lights[lightIndex];
  20129. var shadowGenerator = light.getShadowGenerator();
  20130. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  20131. var shadowMap = (shadowGenerator.getShadowMap());
  20132. if (this.textures.indexOf(shadowMap) !== -1) {
  20133. this._renderTargets.push(shadowMap);
  20134. }
  20135. }
  20136. }
  20137. }
  20138. // Depth renderer
  20139. if (this._depthRenderer) {
  20140. this._renderTargets.push(this._depthRenderer.getDepthMap());
  20141. }
  20142. // Geometry renderer
  20143. if (this._geometryBufferRenderer) {
  20144. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  20145. }
  20146. // RenderPipeline
  20147. if (this._postProcessRenderPipelineManager) {
  20148. this._postProcessRenderPipelineManager.update();
  20149. }
  20150. // Multi-cameras?
  20151. if (this.activeCameras.length > 0) {
  20152. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  20153. if (cameraIndex > 0) {
  20154. this._engine.clear(null, false, true, true);
  20155. }
  20156. this._processSubCameras(this.activeCameras[cameraIndex]);
  20157. }
  20158. }
  20159. else {
  20160. if (!this.activeCamera) {
  20161. throw new Error("No camera defined");
  20162. }
  20163. this._processSubCameras(this.activeCamera);
  20164. }
  20165. // Intersection checks
  20166. this._checkIntersections();
  20167. // Update the audio listener attached to the camera
  20168. if (BABYLON.AudioEngine) {
  20169. this._updateAudioParameters();
  20170. }
  20171. // After render
  20172. if (this.afterRender) {
  20173. this.afterRender();
  20174. }
  20175. this.onAfterRenderObservable.notifyObservers(this);
  20176. // Cleaning
  20177. for (var index = 0; index < this._toBeDisposed.length; index++) {
  20178. var data = this._toBeDisposed.data[index];
  20179. if (data) {
  20180. data.dispose();
  20181. }
  20182. this._toBeDisposed[index] = null;
  20183. }
  20184. this._toBeDisposed.reset();
  20185. if (this.dumpNextRenderTargets) {
  20186. this.dumpNextRenderTargets = false;
  20187. }
  20188. this._activeBones.addCount(0, true);
  20189. this._activeIndices.addCount(0, true);
  20190. this._activeParticles.addCount(0, true);
  20191. };
  20192. Scene.prototype._updateAudioParameters = function () {
  20193. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  20194. return;
  20195. }
  20196. var listeningCamera;
  20197. var audioEngine = BABYLON.Engine.audioEngine;
  20198. if (this.activeCameras.length > 0) {
  20199. listeningCamera = this.activeCameras[0];
  20200. }
  20201. else {
  20202. listeningCamera = this.activeCamera;
  20203. }
  20204. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  20205. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  20206. // for VR cameras
  20207. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  20208. listeningCamera = listeningCamera.rigCameras[0];
  20209. }
  20210. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  20211. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  20212. cameraDirection.normalize();
  20213. // To avoid some errors on GearVR
  20214. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  20215. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  20216. }
  20217. var i;
  20218. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20219. var sound = this.mainSoundTrack.soundCollection[i];
  20220. if (sound.useCustomAttenuation) {
  20221. sound.updateDistanceFromListener();
  20222. }
  20223. }
  20224. for (i = 0; i < this.soundTracks.length; i++) {
  20225. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20226. sound = this.soundTracks[i].soundCollection[j];
  20227. if (sound.useCustomAttenuation) {
  20228. sound.updateDistanceFromListener();
  20229. }
  20230. }
  20231. }
  20232. }
  20233. };
  20234. Object.defineProperty(Scene.prototype, "audioEnabled", {
  20235. // Audio
  20236. get: function () {
  20237. return this._audioEnabled;
  20238. },
  20239. set: function (value) {
  20240. this._audioEnabled = value;
  20241. if (BABYLON.AudioEngine) {
  20242. if (this._audioEnabled) {
  20243. this._enableAudio();
  20244. }
  20245. else {
  20246. this._disableAudio();
  20247. }
  20248. }
  20249. },
  20250. enumerable: true,
  20251. configurable: true
  20252. });
  20253. Scene.prototype._disableAudio = function () {
  20254. var i;
  20255. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20256. this.mainSoundTrack.soundCollection[i].pause();
  20257. }
  20258. for (i = 0; i < this.soundTracks.length; i++) {
  20259. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20260. this.soundTracks[i].soundCollection[j].pause();
  20261. }
  20262. }
  20263. };
  20264. Scene.prototype._enableAudio = function () {
  20265. var i;
  20266. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  20267. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  20268. this.mainSoundTrack.soundCollection[i].play();
  20269. }
  20270. }
  20271. for (i = 0; i < this.soundTracks.length; i++) {
  20272. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  20273. if (this.soundTracks[i].soundCollection[j].isPaused) {
  20274. this.soundTracks[i].soundCollection[j].play();
  20275. }
  20276. }
  20277. }
  20278. };
  20279. Object.defineProperty(Scene.prototype, "headphone", {
  20280. get: function () {
  20281. return this._headphone;
  20282. },
  20283. set: function (value) {
  20284. this._headphone = value;
  20285. if (BABYLON.AudioEngine) {
  20286. if (this._headphone) {
  20287. this._switchAudioModeForHeadphones();
  20288. }
  20289. else {
  20290. this._switchAudioModeForNormalSpeakers();
  20291. }
  20292. }
  20293. },
  20294. enumerable: true,
  20295. configurable: true
  20296. });
  20297. Scene.prototype._switchAudioModeForHeadphones = function () {
  20298. this.mainSoundTrack.switchPanningModelToHRTF();
  20299. for (var i = 0; i < this.soundTracks.length; i++) {
  20300. this.soundTracks[i].switchPanningModelToHRTF();
  20301. }
  20302. };
  20303. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  20304. this.mainSoundTrack.switchPanningModelToEqualPower();
  20305. for (var i = 0; i < this.soundTracks.length; i++) {
  20306. this.soundTracks[i].switchPanningModelToEqualPower();
  20307. }
  20308. };
  20309. Scene.prototype.enableDepthRenderer = function () {
  20310. if (this._depthRenderer) {
  20311. return this._depthRenderer;
  20312. }
  20313. this._depthRenderer = new BABYLON.DepthRenderer(this);
  20314. return this._depthRenderer;
  20315. };
  20316. Scene.prototype.disableDepthRenderer = function () {
  20317. if (!this._depthRenderer) {
  20318. return;
  20319. }
  20320. this._depthRenderer.dispose();
  20321. this._depthRenderer = null;
  20322. };
  20323. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  20324. if (ratio === void 0) { ratio = 1; }
  20325. if (this._geometryBufferRenderer) {
  20326. return this._geometryBufferRenderer;
  20327. }
  20328. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  20329. if (!this._geometryBufferRenderer.isSupported) {
  20330. this._geometryBufferRenderer = null;
  20331. }
  20332. return this._geometryBufferRenderer;
  20333. };
  20334. Scene.prototype.disableGeometryBufferRenderer = function () {
  20335. if (!this._geometryBufferRenderer) {
  20336. return;
  20337. }
  20338. this._geometryBufferRenderer.dispose();
  20339. this._geometryBufferRenderer = null;
  20340. };
  20341. Scene.prototype.freezeMaterials = function () {
  20342. for (var i = 0; i < this.materials.length; i++) {
  20343. this.materials[i].freeze();
  20344. }
  20345. };
  20346. Scene.prototype.unfreezeMaterials = function () {
  20347. for (var i = 0; i < this.materials.length; i++) {
  20348. this.materials[i].unfreeze();
  20349. }
  20350. };
  20351. Scene.prototype.dispose = function () {
  20352. this.beforeRender = null;
  20353. this.afterRender = null;
  20354. this.skeletons = [];
  20355. this.morphTargetManagers = [];
  20356. this.importedMeshesFiles = new Array();
  20357. this.resetCachedMaterial();
  20358. if (this._depthRenderer) {
  20359. this._depthRenderer.dispose();
  20360. }
  20361. if (this._gamepadManager) {
  20362. this._gamepadManager.dispose();
  20363. this._gamepadManager = null;
  20364. }
  20365. // Smart arrays
  20366. if (this.activeCamera) {
  20367. this.activeCamera._activeMeshes.dispose();
  20368. this.activeCamera = null;
  20369. }
  20370. this._activeMeshes.dispose();
  20371. this._renderingManager.dispose();
  20372. this._processedMaterials.dispose();
  20373. this._activeParticleSystems.dispose();
  20374. this._activeSkeletons.dispose();
  20375. this._softwareSkinnedMeshes.dispose();
  20376. this._renderTargets.dispose();
  20377. if (this._boundingBoxRenderer) {
  20378. this._boundingBoxRenderer.dispose();
  20379. }
  20380. this._meshesForIntersections.dispose();
  20381. this._toBeDisposed.dispose();
  20382. // Debug layer
  20383. if (this._debugLayer) {
  20384. this._debugLayer.hide();
  20385. }
  20386. // Events
  20387. this.onDisposeObservable.notifyObservers(this);
  20388. this.onDisposeObservable.clear();
  20389. this.onBeforeRenderObservable.clear();
  20390. this.onAfterRenderObservable.clear();
  20391. this.OnBeforeRenderTargetsRenderObservable.clear();
  20392. this.OnAfterRenderTargetsRenderObservable.clear();
  20393. this.onAfterStepObservable.clear();
  20394. this.onBeforeStepObservable.clear();
  20395. this.onBeforeActiveMeshesEvaluationObservable.clear();
  20396. this.onAfterActiveMeshesEvaluationObservable.clear();
  20397. this.onBeforeParticlesRenderingObservable.clear();
  20398. this.onAfterParticlesRenderingObservable.clear();
  20399. this.onBeforeSpritesRenderingObservable.clear();
  20400. this.onAfterSpritesRenderingObservable.clear();
  20401. this.onBeforeDrawPhaseObservable.clear();
  20402. this.onAfterDrawPhaseObservable.clear();
  20403. this.onBeforePhysicsObservable.clear();
  20404. this.onAfterPhysicsObservable.clear();
  20405. this.onBeforeAnimationsObservable.clear();
  20406. this.onAfterAnimationsObservable.clear();
  20407. this.onDataLoadedObservable.clear();
  20408. this.detachControl();
  20409. // Release sounds & sounds tracks
  20410. if (BABYLON.AudioEngine) {
  20411. this.disposeSounds();
  20412. }
  20413. // VR Helper
  20414. if (this.VRHelper) {
  20415. this.VRHelper.dispose();
  20416. }
  20417. // Detach cameras
  20418. var canvas = this._engine.getRenderingCanvas();
  20419. if (canvas) {
  20420. var index;
  20421. for (index = 0; index < this.cameras.length; index++) {
  20422. this.cameras[index].detachControl(canvas);
  20423. }
  20424. }
  20425. // Release lights
  20426. while (this.lights.length) {
  20427. this.lights[0].dispose();
  20428. }
  20429. // Release meshes
  20430. while (this.meshes.length) {
  20431. this.meshes[0].dispose(true);
  20432. }
  20433. // Release cameras
  20434. while (this.cameras.length) {
  20435. this.cameras[0].dispose();
  20436. }
  20437. // Release materials
  20438. if (this.defaultMaterial) {
  20439. this.defaultMaterial.dispose();
  20440. }
  20441. while (this.multiMaterials.length) {
  20442. this.multiMaterials[0].dispose();
  20443. }
  20444. while (this.materials.length) {
  20445. this.materials[0].dispose();
  20446. }
  20447. // Release particles
  20448. while (this.particleSystems.length) {
  20449. this.particleSystems[0].dispose();
  20450. }
  20451. // Release sprites
  20452. while (this.spriteManagers.length) {
  20453. this.spriteManagers[0].dispose();
  20454. }
  20455. // Release postProcesses
  20456. while (this.postProcesses.length) {
  20457. this.postProcesses[0].dispose();
  20458. }
  20459. // Release layers
  20460. while (this.layers.length) {
  20461. this.layers[0].dispose();
  20462. }
  20463. while (this.highlightLayers.length) {
  20464. this.highlightLayers[0].dispose();
  20465. }
  20466. // Release textures
  20467. while (this.textures.length) {
  20468. this.textures[0].dispose();
  20469. }
  20470. // Release UBO
  20471. this._sceneUbo.dispose();
  20472. if (this._alternateSceneUbo) {
  20473. this._alternateSceneUbo.dispose();
  20474. }
  20475. // Post-processes
  20476. this.postProcessManager.dispose();
  20477. if (this._postProcessRenderPipelineManager) {
  20478. this._postProcessRenderPipelineManager.dispose();
  20479. }
  20480. // Physics
  20481. if (this._physicsEngine) {
  20482. this.disablePhysicsEngine();
  20483. }
  20484. // Remove from engine
  20485. index = this._engine.scenes.indexOf(this);
  20486. if (index > -1) {
  20487. this._engine.scenes.splice(index, 1);
  20488. }
  20489. this._engine.wipeCaches();
  20490. this._isDisposed = true;
  20491. };
  20492. Object.defineProperty(Scene.prototype, "isDisposed", {
  20493. get: function () {
  20494. return this._isDisposed;
  20495. },
  20496. enumerable: true,
  20497. configurable: true
  20498. });
  20499. // Release sounds & sounds tracks
  20500. Scene.prototype.disposeSounds = function () {
  20501. if (!this._mainSoundTrack) {
  20502. return;
  20503. }
  20504. this.mainSoundTrack.dispose();
  20505. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  20506. this.soundTracks[scIndex].dispose();
  20507. }
  20508. };
  20509. // Octrees
  20510. Scene.prototype.getWorldExtends = function () {
  20511. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20512. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20513. for (var index = 0; index < this.meshes.length; index++) {
  20514. var mesh = this.meshes[index];
  20515. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  20516. continue;
  20517. }
  20518. mesh.computeWorldMatrix(true);
  20519. var boundingInfo = mesh.getBoundingInfo();
  20520. if (boundingInfo) {
  20521. var minBox = boundingInfo.boundingBox.minimumWorld;
  20522. var maxBox = boundingInfo.boundingBox.maximumWorld;
  20523. BABYLON.Tools.CheckExtends(minBox, min, max);
  20524. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20525. }
  20526. }
  20527. return {
  20528. min: min,
  20529. max: max
  20530. };
  20531. };
  20532. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  20533. if (maxCapacity === void 0) { maxCapacity = 64; }
  20534. if (maxDepth === void 0) { maxDepth = 2; }
  20535. if (!this._selectionOctree) {
  20536. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  20537. }
  20538. var worldExtends = this.getWorldExtends();
  20539. // Update octree
  20540. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  20541. return this._selectionOctree;
  20542. };
  20543. // Picking
  20544. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  20545. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  20546. var engine = this._engine;
  20547. if (!camera) {
  20548. if (!this.activeCamera)
  20549. throw new Error("Active camera not set");
  20550. camera = this.activeCamera;
  20551. }
  20552. var cameraViewport = camera.viewport;
  20553. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20554. // Moving coordinates to local viewport world
  20555. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20556. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20557. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  20558. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  20559. };
  20560. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  20561. if (!BABYLON.PickingInfo) {
  20562. return null;
  20563. }
  20564. var engine = this._engine;
  20565. if (!camera) {
  20566. if (!this.activeCamera)
  20567. throw new Error("Active camera not set");
  20568. camera = this.activeCamera;
  20569. }
  20570. var cameraViewport = camera.viewport;
  20571. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  20572. var identity = BABYLON.Matrix.Identity();
  20573. // Moving coordinates to local viewport world
  20574. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  20575. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  20576. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  20577. };
  20578. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  20579. if (!BABYLON.PickingInfo) {
  20580. return null;
  20581. }
  20582. var pickingInfo = null;
  20583. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20584. var mesh = this.meshes[meshIndex];
  20585. if (predicate) {
  20586. if (!predicate(mesh)) {
  20587. continue;
  20588. }
  20589. }
  20590. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20591. continue;
  20592. }
  20593. var world = mesh.getWorldMatrix();
  20594. var ray = rayFunction(world);
  20595. var result = mesh.intersects(ray, fastCheck);
  20596. if (!result || !result.hit)
  20597. continue;
  20598. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20599. continue;
  20600. pickingInfo = result;
  20601. if (fastCheck) {
  20602. break;
  20603. }
  20604. }
  20605. return pickingInfo || new BABYLON.PickingInfo();
  20606. };
  20607. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  20608. if (!BABYLON.PickingInfo) {
  20609. return null;
  20610. }
  20611. var pickingInfos = new Array();
  20612. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  20613. var mesh = this.meshes[meshIndex];
  20614. if (predicate) {
  20615. if (!predicate(mesh)) {
  20616. continue;
  20617. }
  20618. }
  20619. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  20620. continue;
  20621. }
  20622. var world = mesh.getWorldMatrix();
  20623. var ray = rayFunction(world);
  20624. var result = mesh.intersects(ray, false);
  20625. if (!result || !result.hit)
  20626. continue;
  20627. pickingInfos.push(result);
  20628. }
  20629. return pickingInfos;
  20630. };
  20631. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  20632. if (!BABYLON.PickingInfo) {
  20633. return null;
  20634. }
  20635. var pickingInfo = null;
  20636. if (!camera) {
  20637. if (!this.activeCamera) {
  20638. return null;
  20639. }
  20640. camera = this.activeCamera;
  20641. }
  20642. if (this.spriteManagers.length > 0) {
  20643. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  20644. var spriteManager = this.spriteManagers[spriteIndex];
  20645. if (!spriteManager.isPickable) {
  20646. continue;
  20647. }
  20648. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  20649. if (!result || !result.hit)
  20650. continue;
  20651. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  20652. continue;
  20653. pickingInfo = result;
  20654. if (fastCheck) {
  20655. break;
  20656. }
  20657. }
  20658. }
  20659. return pickingInfo || new BABYLON.PickingInfo();
  20660. };
  20661. /** Launch a ray to try to pick a mesh in the scene
  20662. * @param x position on screen
  20663. * @param y position on screen
  20664. * @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
  20665. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20666. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20667. */
  20668. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  20669. var _this = this;
  20670. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, fastCheck);
  20671. };
  20672. /** Launch a ray to try to pick a sprite in the scene
  20673. * @param x position on screen
  20674. * @param y position on screen
  20675. * @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
  20676. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20677. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20678. */
  20679. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  20680. var ray = this.createPickingRayInCameraSpace(x, y, camera);
  20681. if (!ray) {
  20682. return null;
  20683. }
  20684. return this._internalPickSprites(ray, predicate, fastCheck, camera);
  20685. };
  20686. /** Use the given ray to pick a mesh in the scene
  20687. * @param ray The ray to use to pick meshes
  20688. * @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
  20689. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  20690. */
  20691. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  20692. var _this = this;
  20693. return this._internalPick(function (world) {
  20694. if (!_this._pickWithRayInverseMatrix) {
  20695. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20696. }
  20697. world.invertToRef(_this._pickWithRayInverseMatrix);
  20698. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20699. }, predicate, fastCheck);
  20700. };
  20701. /**
  20702. * Launch a ray to try to pick a mesh in the scene
  20703. * @param x X position on screen
  20704. * @param y Y position on screen
  20705. * @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
  20706. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  20707. */
  20708. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  20709. var _this = this;
  20710. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  20711. };
  20712. /**
  20713. * Launch a ray to try to pick a mesh in the scene
  20714. * @param ray Ray to use
  20715. * @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
  20716. */
  20717. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  20718. var _this = this;
  20719. return this._internalMultiPick(function (world) {
  20720. if (!_this._pickWithRayInverseMatrix) {
  20721. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  20722. }
  20723. world.invertToRef(_this._pickWithRayInverseMatrix);
  20724. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  20725. }, predicate);
  20726. };
  20727. Scene.prototype.setPointerOverMesh = function (mesh) {
  20728. if (this._pointerOverMesh === mesh) {
  20729. return;
  20730. }
  20731. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20732. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20733. }
  20734. this._pointerOverMesh = mesh;
  20735. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  20736. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  20737. }
  20738. };
  20739. Scene.prototype.getPointerOverMesh = function () {
  20740. return this._pointerOverMesh;
  20741. };
  20742. Scene.prototype.setPointerOverSprite = function (sprite) {
  20743. if (this._pointerOverSprite === sprite) {
  20744. return;
  20745. }
  20746. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20747. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20748. }
  20749. this._pointerOverSprite = sprite;
  20750. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  20751. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  20752. }
  20753. };
  20754. Scene.prototype.getPointerOverSprite = function () {
  20755. return this._pointerOverSprite;
  20756. };
  20757. // Physics
  20758. Scene.prototype.getPhysicsEngine = function () {
  20759. return this._physicsEngine;
  20760. };
  20761. /**
  20762. * Enables physics to the current scene
  20763. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  20764. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  20765. * @return {boolean} was the physics engine initialized
  20766. */
  20767. Scene.prototype.enablePhysics = function (gravity, plugin) {
  20768. if (gravity === void 0) { gravity = null; }
  20769. if (this._physicsEngine) {
  20770. return true;
  20771. }
  20772. try {
  20773. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  20774. return true;
  20775. }
  20776. catch (e) {
  20777. BABYLON.Tools.Error(e.message);
  20778. return false;
  20779. }
  20780. };
  20781. Scene.prototype.disablePhysicsEngine = function () {
  20782. if (!this._physicsEngine) {
  20783. return;
  20784. }
  20785. this._physicsEngine.dispose();
  20786. this._physicsEngine = null;
  20787. };
  20788. Scene.prototype.isPhysicsEnabled = function () {
  20789. return this._physicsEngine !== undefined;
  20790. };
  20791. Scene.prototype.deleteCompoundImpostor = function (compound) {
  20792. var mesh = compound.parts[0].mesh;
  20793. if (mesh.physicsImpostor) {
  20794. mesh.physicsImpostor.dispose();
  20795. mesh.physicsImpostor = null;
  20796. }
  20797. };
  20798. // Misc.
  20799. Scene.prototype._rebuildGeometries = function () {
  20800. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  20801. var geometry = _a[_i];
  20802. geometry._rebuild();
  20803. }
  20804. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  20805. var mesh = _c[_b];
  20806. mesh._rebuild();
  20807. }
  20808. if (this.postProcessManager) {
  20809. this.postProcessManager._rebuild();
  20810. }
  20811. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  20812. var layer = _e[_d];
  20813. layer._rebuild();
  20814. }
  20815. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  20816. var highlightLayer = _g[_f];
  20817. highlightLayer._rebuild();
  20818. }
  20819. if (this._boundingBoxRenderer) {
  20820. this._boundingBoxRenderer._rebuild();
  20821. }
  20822. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  20823. var system = _j[_h];
  20824. system.rebuild();
  20825. }
  20826. if (this._postProcessRenderPipelineManager) {
  20827. this._postProcessRenderPipelineManager._rebuild();
  20828. }
  20829. };
  20830. Scene.prototype._rebuildTextures = function () {
  20831. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  20832. var texture = _a[_i];
  20833. texture._rebuild();
  20834. }
  20835. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20836. };
  20837. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  20838. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  20839. if (replace === void 0) { replace = false; }
  20840. if (attachCameraControls === void 0) { attachCameraControls = false; }
  20841. // Dispose existing camera or light in replace mode.
  20842. if (replace) {
  20843. if (this.activeCamera) {
  20844. this.activeCamera.dispose();
  20845. this.activeCamera = null;
  20846. }
  20847. if (this.lights) {
  20848. for (var i = 0; i < this.lights.length; i++) {
  20849. this.lights[i].dispose();
  20850. }
  20851. }
  20852. }
  20853. // Light
  20854. if (this.lights.length === 0) {
  20855. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  20856. }
  20857. // Camera
  20858. if (!this.activeCamera) {
  20859. var worldExtends = this.getWorldExtends();
  20860. var worldSize = worldExtends.max.subtract(worldExtends.min);
  20861. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  20862. var camera;
  20863. var radius = worldSize.length() * 1.5;
  20864. if (createArcRotateCamera) {
  20865. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  20866. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  20867. arcRotateCamera.wheelPrecision = 100 / radius;
  20868. camera = arcRotateCamera;
  20869. }
  20870. else {
  20871. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  20872. freeCamera.setTarget(worldCenter);
  20873. camera = freeCamera;
  20874. }
  20875. camera.minZ = radius * 0.01;
  20876. camera.maxZ = radius * 100;
  20877. camera.speed = radius * 0.2;
  20878. this.activeCamera = camera;
  20879. var canvas = this.getEngine().getRenderingCanvas();
  20880. if (attachCameraControls && canvas) {
  20881. camera.attachControl(canvas);
  20882. }
  20883. }
  20884. };
  20885. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  20886. if (pbr === void 0) { pbr = false; }
  20887. if (scale === void 0) { scale = 1000; }
  20888. if (blur === void 0) { blur = 0; }
  20889. if (environmentTexture) {
  20890. this.environmentTexture = environmentTexture;
  20891. }
  20892. if (!this.environmentTexture) {
  20893. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  20894. return null;
  20895. }
  20896. // Skybox
  20897. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  20898. if (pbr) {
  20899. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  20900. hdrSkyboxMaterial.backFaceCulling = false;
  20901. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20902. if (hdrSkyboxMaterial.reflectionTexture) {
  20903. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20904. }
  20905. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  20906. hdrSkyboxMaterial.disableLighting = true;
  20907. hdrSkyboxMaterial.twoSidedLighting = true;
  20908. hdrSkybox.infiniteDistance = true;
  20909. hdrSkybox.material = hdrSkyboxMaterial;
  20910. }
  20911. else {
  20912. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  20913. skyboxMaterial.backFaceCulling = false;
  20914. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  20915. if (skyboxMaterial.reflectionTexture) {
  20916. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  20917. }
  20918. skyboxMaterial.disableLighting = true;
  20919. hdrSkybox.infiniteDistance = true;
  20920. hdrSkybox.material = skyboxMaterial;
  20921. }
  20922. return hdrSkybox;
  20923. };
  20924. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  20925. if (webVROptions === void 0) { webVROptions = {}; }
  20926. this.VRHelper = new BABYLON.VRExperienceHelper(this, webVROptions);
  20927. };
  20928. // Tags
  20929. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  20930. if (tagsQuery === undefined) {
  20931. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  20932. return list;
  20933. }
  20934. var listByTags = [];
  20935. forEach = forEach || (function (item) { return; });
  20936. for (var i in list) {
  20937. var item = list[i];
  20938. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  20939. listByTags.push(item);
  20940. forEach(item);
  20941. }
  20942. }
  20943. return listByTags;
  20944. };
  20945. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  20946. return this._getByTags(this.meshes, tagsQuery, forEach);
  20947. };
  20948. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20949. return this._getByTags(this.cameras, tagsQuery, forEach);
  20950. };
  20951. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20952. return this._getByTags(this.lights, tagsQuery, forEach);
  20953. };
  20954. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20955. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20956. };
  20957. /**
  20958. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20959. * This allowed control for front to back rendering or reversly depending of the special needs.
  20960. *
  20961. * @param renderingGroupId The rendering group id corresponding to its index
  20962. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20963. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20964. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20965. */
  20966. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20967. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20968. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20969. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20970. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20971. };
  20972. /**
  20973. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20974. *
  20975. * @param renderingGroupId The rendering group id corresponding to its index
  20976. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20977. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20978. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20979. */
  20980. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20981. if (depth === void 0) { depth = true; }
  20982. if (stencil === void 0) { stencil = true; }
  20983. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20984. };
  20985. /**
  20986. * Will flag all materials as dirty to trigger new shader compilation
  20987. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  20988. */
  20989. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  20990. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  20991. var material = _a[_i];
  20992. if (predicate && !predicate(material)) {
  20993. continue;
  20994. }
  20995. material.markAsDirty(flag);
  20996. }
  20997. };
  20998. // Statics
  20999. Scene._FOGMODE_NONE = 0;
  21000. Scene._FOGMODE_EXP = 1;
  21001. Scene._FOGMODE_EXP2 = 2;
  21002. Scene._FOGMODE_LINEAR = 3;
  21003. Scene._uniqueIdCounter = 0;
  21004. Scene.MinDeltaTime = 1.0;
  21005. Scene.MaxDeltaTime = 1000.0;
  21006. /** The distance in pixel that you have to move to prevent some events */
  21007. Scene.DragMovementThreshold = 10; // in pixels
  21008. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  21009. Scene.LongPressDelay = 500; // in milliseconds
  21010. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  21011. Scene.DoubleClickDelay = 300; // in milliseconds
  21012. /** If you need to check double click without raising a single click at first click, enable this flag */
  21013. Scene.ExclusiveDoubleClickMode = false;
  21014. return Scene;
  21015. }());
  21016. BABYLON.Scene = Scene;
  21017. })(BABYLON || (BABYLON = {}));
  21018. //# sourceMappingURL=babylon.scene.js.map
  21019. var BABYLON;
  21020. (function (BABYLON) {
  21021. var Buffer = /** @class */ (function () {
  21022. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  21023. if (instanced === void 0) { instanced = false; }
  21024. if (engine instanceof BABYLON.Mesh) {
  21025. this._engine = engine.getScene().getEngine();
  21026. }
  21027. else {
  21028. this._engine = engine;
  21029. }
  21030. this._updatable = updatable;
  21031. this._data = data;
  21032. this._strideSize = stride;
  21033. if (!postponeInternalCreation) {
  21034. this.create();
  21035. }
  21036. this._instanced = instanced;
  21037. this._instanceDivisor = instanced ? 1 : 0;
  21038. }
  21039. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  21040. // a lot of these parameters are ignored as they are overriden by the buffer
  21041. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  21042. };
  21043. // Properties
  21044. Buffer.prototype.isUpdatable = function () {
  21045. return this._updatable;
  21046. };
  21047. Buffer.prototype.getData = function () {
  21048. return this._data;
  21049. };
  21050. Buffer.prototype.getBuffer = function () {
  21051. return this._buffer;
  21052. };
  21053. Buffer.prototype.getStrideSize = function () {
  21054. return this._strideSize;
  21055. };
  21056. Buffer.prototype.getIsInstanced = function () {
  21057. return this._instanced;
  21058. };
  21059. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  21060. get: function () {
  21061. return this._instanceDivisor;
  21062. },
  21063. set: function (value) {
  21064. this._instanceDivisor = value;
  21065. if (value == 0) {
  21066. this._instanced = false;
  21067. }
  21068. else {
  21069. this._instanced = true;
  21070. }
  21071. },
  21072. enumerable: true,
  21073. configurable: true
  21074. });
  21075. // Methods
  21076. Buffer.prototype.create = function (data) {
  21077. if (data === void 0) { data = null; }
  21078. if (!data && this._buffer) {
  21079. return; // nothing to do
  21080. }
  21081. data = data || this._data;
  21082. if (!data) {
  21083. return;
  21084. }
  21085. if (!this._buffer) {
  21086. if (this._updatable) {
  21087. this._buffer = this._engine.createDynamicVertexBuffer(data);
  21088. this._data = data;
  21089. }
  21090. else {
  21091. this._buffer = this._engine.createVertexBuffer(data);
  21092. }
  21093. }
  21094. else if (this._updatable) {
  21095. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  21096. this._data = data;
  21097. }
  21098. };
  21099. Buffer.prototype._rebuild = function () {
  21100. this._buffer = null;
  21101. this.create(this._data);
  21102. };
  21103. Buffer.prototype.update = function (data) {
  21104. this.create(data);
  21105. };
  21106. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  21107. if (!this._buffer) {
  21108. return;
  21109. }
  21110. if (this._updatable) {
  21111. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  21112. this._data = null;
  21113. }
  21114. };
  21115. Buffer.prototype.dispose = function () {
  21116. if (!this._buffer) {
  21117. return;
  21118. }
  21119. if (this._engine._releaseBuffer(this._buffer)) {
  21120. this._buffer = null;
  21121. }
  21122. };
  21123. return Buffer;
  21124. }());
  21125. BABYLON.Buffer = Buffer;
  21126. })(BABYLON || (BABYLON = {}));
  21127. //# sourceMappingURL=babylon.buffer.js.map
  21128. var BABYLON;
  21129. (function (BABYLON) {
  21130. var VertexBuffer = /** @class */ (function () {
  21131. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  21132. if (!stride) {
  21133. // Deduce stride from kind
  21134. switch (kind) {
  21135. case VertexBuffer.PositionKind:
  21136. stride = 3;
  21137. break;
  21138. case VertexBuffer.NormalKind:
  21139. stride = 3;
  21140. break;
  21141. case VertexBuffer.UVKind:
  21142. case VertexBuffer.UV2Kind:
  21143. case VertexBuffer.UV3Kind:
  21144. case VertexBuffer.UV4Kind:
  21145. case VertexBuffer.UV5Kind:
  21146. case VertexBuffer.UV6Kind:
  21147. stride = 2;
  21148. break;
  21149. case VertexBuffer.TangentKind:
  21150. case VertexBuffer.ColorKind:
  21151. stride = 4;
  21152. break;
  21153. case VertexBuffer.MatricesIndicesKind:
  21154. case VertexBuffer.MatricesIndicesExtraKind:
  21155. stride = 4;
  21156. break;
  21157. case VertexBuffer.MatricesWeightsKind:
  21158. case VertexBuffer.MatricesWeightsExtraKind:
  21159. default:
  21160. stride = 4;
  21161. break;
  21162. }
  21163. }
  21164. if (data instanceof BABYLON.Buffer) {
  21165. if (!stride) {
  21166. stride = data.getStrideSize();
  21167. }
  21168. this._buffer = data;
  21169. this._ownsBuffer = false;
  21170. }
  21171. else {
  21172. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  21173. this._ownsBuffer = true;
  21174. }
  21175. this._stride = stride;
  21176. this._offset = offset ? offset : 0;
  21177. this._size = size ? size : stride;
  21178. this._kind = kind;
  21179. }
  21180. VertexBuffer.prototype._rebuild = function () {
  21181. if (!this._buffer) {
  21182. return;
  21183. }
  21184. this._buffer._rebuild();
  21185. };
  21186. /**
  21187. * Returns the kind of the VertexBuffer (string).
  21188. */
  21189. VertexBuffer.prototype.getKind = function () {
  21190. return this._kind;
  21191. };
  21192. // Properties
  21193. /**
  21194. * Boolean : is the VertexBuffer updatable ?
  21195. */
  21196. VertexBuffer.prototype.isUpdatable = function () {
  21197. return this._buffer.isUpdatable();
  21198. };
  21199. /**
  21200. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  21201. */
  21202. VertexBuffer.prototype.getData = function () {
  21203. return this._buffer.getData();
  21204. };
  21205. /**
  21206. * Returns the WebGLBuffer associated to the VertexBuffer.
  21207. */
  21208. VertexBuffer.prototype.getBuffer = function () {
  21209. return this._buffer.getBuffer();
  21210. };
  21211. /**
  21212. * Returns the stride of the VertexBuffer (integer).
  21213. */
  21214. VertexBuffer.prototype.getStrideSize = function () {
  21215. return this._stride;
  21216. };
  21217. /**
  21218. * Returns the offset (integer).
  21219. */
  21220. VertexBuffer.prototype.getOffset = function () {
  21221. return this._offset;
  21222. };
  21223. /**
  21224. * Returns the VertexBuffer total size (integer).
  21225. */
  21226. VertexBuffer.prototype.getSize = function () {
  21227. return this._size;
  21228. };
  21229. /**
  21230. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  21231. */
  21232. VertexBuffer.prototype.getIsInstanced = function () {
  21233. return this._buffer.getIsInstanced();
  21234. };
  21235. /**
  21236. * Returns the instancing divisor, zero for non-instanced (integer).
  21237. */
  21238. VertexBuffer.prototype.getInstanceDivisor = function () {
  21239. return this._buffer.instanceDivisor;
  21240. };
  21241. // Methods
  21242. /**
  21243. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  21244. * Returns the created WebGLBuffer.
  21245. */
  21246. VertexBuffer.prototype.create = function (data) {
  21247. return this._buffer.create(data);
  21248. };
  21249. /**
  21250. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21251. * Returns the updated WebGLBuffer.
  21252. */
  21253. VertexBuffer.prototype.update = function (data) {
  21254. return this._buffer.update(data);
  21255. };
  21256. /**
  21257. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  21258. * Returns the directly updated WebGLBuffer.
  21259. */
  21260. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  21261. return this._buffer.updateDirectly(data, offset);
  21262. };
  21263. /**
  21264. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  21265. */
  21266. VertexBuffer.prototype.dispose = function () {
  21267. if (this._ownsBuffer) {
  21268. this._buffer.dispose();
  21269. }
  21270. };
  21271. Object.defineProperty(VertexBuffer, "PositionKind", {
  21272. get: function () {
  21273. return VertexBuffer._PositionKind;
  21274. },
  21275. enumerable: true,
  21276. configurable: true
  21277. });
  21278. Object.defineProperty(VertexBuffer, "NormalKind", {
  21279. get: function () {
  21280. return VertexBuffer._NormalKind;
  21281. },
  21282. enumerable: true,
  21283. configurable: true
  21284. });
  21285. Object.defineProperty(VertexBuffer, "TangentKind", {
  21286. get: function () {
  21287. return VertexBuffer._TangentKind;
  21288. },
  21289. enumerable: true,
  21290. configurable: true
  21291. });
  21292. Object.defineProperty(VertexBuffer, "UVKind", {
  21293. get: function () {
  21294. return VertexBuffer._UVKind;
  21295. },
  21296. enumerable: true,
  21297. configurable: true
  21298. });
  21299. Object.defineProperty(VertexBuffer, "UV2Kind", {
  21300. get: function () {
  21301. return VertexBuffer._UV2Kind;
  21302. },
  21303. enumerable: true,
  21304. configurable: true
  21305. });
  21306. Object.defineProperty(VertexBuffer, "UV3Kind", {
  21307. get: function () {
  21308. return VertexBuffer._UV3Kind;
  21309. },
  21310. enumerable: true,
  21311. configurable: true
  21312. });
  21313. Object.defineProperty(VertexBuffer, "UV4Kind", {
  21314. get: function () {
  21315. return VertexBuffer._UV4Kind;
  21316. },
  21317. enumerable: true,
  21318. configurable: true
  21319. });
  21320. Object.defineProperty(VertexBuffer, "UV5Kind", {
  21321. get: function () {
  21322. return VertexBuffer._UV5Kind;
  21323. },
  21324. enumerable: true,
  21325. configurable: true
  21326. });
  21327. Object.defineProperty(VertexBuffer, "UV6Kind", {
  21328. get: function () {
  21329. return VertexBuffer._UV6Kind;
  21330. },
  21331. enumerable: true,
  21332. configurable: true
  21333. });
  21334. Object.defineProperty(VertexBuffer, "ColorKind", {
  21335. get: function () {
  21336. return VertexBuffer._ColorKind;
  21337. },
  21338. enumerable: true,
  21339. configurable: true
  21340. });
  21341. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  21342. get: function () {
  21343. return VertexBuffer._MatricesIndicesKind;
  21344. },
  21345. enumerable: true,
  21346. configurable: true
  21347. });
  21348. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  21349. get: function () {
  21350. return VertexBuffer._MatricesWeightsKind;
  21351. },
  21352. enumerable: true,
  21353. configurable: true
  21354. });
  21355. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  21356. get: function () {
  21357. return VertexBuffer._MatricesIndicesExtraKind;
  21358. },
  21359. enumerable: true,
  21360. configurable: true
  21361. });
  21362. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  21363. get: function () {
  21364. return VertexBuffer._MatricesWeightsExtraKind;
  21365. },
  21366. enumerable: true,
  21367. configurable: true
  21368. });
  21369. // Enums
  21370. VertexBuffer._PositionKind = "position";
  21371. VertexBuffer._NormalKind = "normal";
  21372. VertexBuffer._TangentKind = "tangent";
  21373. VertexBuffer._UVKind = "uv";
  21374. VertexBuffer._UV2Kind = "uv2";
  21375. VertexBuffer._UV3Kind = "uv3";
  21376. VertexBuffer._UV4Kind = "uv4";
  21377. VertexBuffer._UV5Kind = "uv5";
  21378. VertexBuffer._UV6Kind = "uv6";
  21379. VertexBuffer._ColorKind = "color";
  21380. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  21381. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  21382. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  21383. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  21384. return VertexBuffer;
  21385. }());
  21386. BABYLON.VertexBuffer = VertexBuffer;
  21387. })(BABYLON || (BABYLON = {}));
  21388. //# sourceMappingURL=babylon.vertexBuffer.js.map
  21389. var BABYLON;
  21390. (function (BABYLON) {
  21391. var InternalTexture = /** @class */ (function () {
  21392. function InternalTexture(engine, dataSource) {
  21393. this.onLoadedObservable = new BABYLON.Observable();
  21394. // Private
  21395. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  21396. this._references = 1;
  21397. this._engine = engine;
  21398. this._dataSource = dataSource;
  21399. this._webGLTexture = engine._createTexture();
  21400. }
  21401. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  21402. get: function () {
  21403. return this._dataSource;
  21404. },
  21405. enumerable: true,
  21406. configurable: true
  21407. });
  21408. InternalTexture.prototype.incrementReferences = function () {
  21409. this._references++;
  21410. };
  21411. InternalTexture.prototype.updateSize = function (width, height, depth) {
  21412. if (depth === void 0) { depth = 1; }
  21413. this.width = width;
  21414. this.height = height;
  21415. this.depth = depth;
  21416. this.baseWidth = width;
  21417. this.baseHeight = height;
  21418. this.baseDepth = depth;
  21419. this._size = width * height * depth;
  21420. };
  21421. InternalTexture.prototype._rebuild = function () {
  21422. var _this = this;
  21423. var proxy;
  21424. this.isReady = false;
  21425. this._cachedCoordinatesMode = null;
  21426. this._cachedWrapU = null;
  21427. this._cachedWrapV = null;
  21428. this._cachedAnisotropicFilteringLevel = null;
  21429. switch (this._dataSource) {
  21430. case InternalTexture.DATASOURCE_TEMP:
  21431. return;
  21432. case InternalTexture.DATASOURCE_URL:
  21433. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  21434. _this.isReady = true;
  21435. }, null, this._buffer, undefined, this.format);
  21436. proxy._swapAndDie(this);
  21437. return;
  21438. case InternalTexture.DATASOURCE_RAW:
  21439. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21440. proxy._swapAndDie(this);
  21441. this.isReady = true;
  21442. return;
  21443. case InternalTexture.DATASOURCE_RAW3D:
  21444. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21445. proxy._swapAndDie(this);
  21446. this.isReady = true;
  21447. return;
  21448. case InternalTexture.DATASOURCE_DYNAMIC:
  21449. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  21450. proxy._swapAndDie(this);
  21451. // The engine will make sure to update content so no need to flag it as isReady = true
  21452. return;
  21453. case InternalTexture.DATASOURCE_RENDERTARGET:
  21454. var options = new BABYLON.RenderTargetCreationOptions();
  21455. options.generateDepthBuffer = this._generateDepthBuffer;
  21456. options.generateMipMaps = this.generateMipMaps;
  21457. options.generateStencilBuffer = this._generateStencilBuffer;
  21458. options.samplingMode = this.samplingMode;
  21459. options.type = this.type;
  21460. if (this.isCube) {
  21461. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  21462. }
  21463. else {
  21464. var size = {
  21465. width: this.width,
  21466. height: this.height
  21467. };
  21468. proxy = this._engine.createRenderTargetTexture(size, options);
  21469. }
  21470. proxy._swapAndDie(this);
  21471. this.isReady = true;
  21472. return;
  21473. case InternalTexture.DATASOURCE_CUBE:
  21474. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  21475. _this.isReady = true;
  21476. }, null, this.format, this._extension);
  21477. proxy._swapAndDie(this);
  21478. return;
  21479. case InternalTexture.DATASOURCE_CUBERAW:
  21480. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  21481. proxy._swapAndDie(this);
  21482. this.isReady = true;
  21483. return;
  21484. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  21485. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  21486. if (proxy) {
  21487. proxy._swapAndDie(_this);
  21488. }
  21489. _this.isReady = true;
  21490. }, null, this.format, this._extension);
  21491. return;
  21492. }
  21493. };
  21494. InternalTexture.prototype._swapAndDie = function (target) {
  21495. target._webGLTexture = this._webGLTexture;
  21496. if (this._framebuffer) {
  21497. target._framebuffer = this._framebuffer;
  21498. }
  21499. if (this._depthStencilBuffer) {
  21500. target._depthStencilBuffer = this._depthStencilBuffer;
  21501. }
  21502. if (this._lodTextureHigh) {
  21503. if (target._lodTextureHigh) {
  21504. target._lodTextureHigh.dispose();
  21505. }
  21506. target._lodTextureHigh = this._lodTextureHigh;
  21507. }
  21508. if (this._lodTextureMid) {
  21509. if (target._lodTextureMid) {
  21510. target._lodTextureMid.dispose();
  21511. }
  21512. target._lodTextureMid = this._lodTextureMid;
  21513. }
  21514. if (this._lodTextureLow) {
  21515. if (target._lodTextureLow) {
  21516. target._lodTextureLow.dispose();
  21517. }
  21518. target._lodTextureLow = this._lodTextureLow;
  21519. }
  21520. var cache = this._engine.getLoadedTexturesCache();
  21521. var index = cache.indexOf(this);
  21522. if (index !== -1) {
  21523. cache.splice(index, 1);
  21524. }
  21525. };
  21526. InternalTexture.prototype.dispose = function () {
  21527. if (!this._webGLTexture) {
  21528. return;
  21529. }
  21530. this._references--;
  21531. if (this._references === 0) {
  21532. this._engine._releaseTexture(this);
  21533. this._webGLTexture = null;
  21534. }
  21535. };
  21536. InternalTexture.DATASOURCE_UNKNOWN = 0;
  21537. InternalTexture.DATASOURCE_URL = 1;
  21538. InternalTexture.DATASOURCE_TEMP = 2;
  21539. InternalTexture.DATASOURCE_RAW = 3;
  21540. InternalTexture.DATASOURCE_DYNAMIC = 4;
  21541. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  21542. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  21543. InternalTexture.DATASOURCE_CUBE = 7;
  21544. InternalTexture.DATASOURCE_CUBERAW = 8;
  21545. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  21546. InternalTexture.DATASOURCE_RAW3D = 10;
  21547. return InternalTexture;
  21548. }());
  21549. BABYLON.InternalTexture = InternalTexture;
  21550. })(BABYLON || (BABYLON = {}));
  21551. //# sourceMappingURL=babylon.internalTexture.js.map
  21552. var BABYLON;
  21553. (function (BABYLON) {
  21554. var BaseTexture = /** @class */ (function () {
  21555. function BaseTexture(scene) {
  21556. this._hasAlpha = false;
  21557. this.getAlphaFromRGB = false;
  21558. this.level = 1;
  21559. this.coordinatesIndex = 0;
  21560. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  21561. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  21562. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  21563. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  21564. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  21565. this.isCube = false;
  21566. this.is3D = false;
  21567. this.gammaSpace = true;
  21568. this.invertZ = false;
  21569. this.lodLevelInAlpha = false;
  21570. this.lodGenerationOffset = 0.0;
  21571. this.lodGenerationScale = 0.8;
  21572. this.isRenderTarget = false;
  21573. this.animations = new Array();
  21574. /**
  21575. * An event triggered when the texture is disposed.
  21576. * @type {BABYLON.Observable}
  21577. */
  21578. this.onDisposeObservable = new BABYLON.Observable();
  21579. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  21580. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  21581. if (this._scene) {
  21582. this._scene.textures.push(this);
  21583. }
  21584. this._uid = null;
  21585. }
  21586. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  21587. get: function () {
  21588. return this._hasAlpha;
  21589. },
  21590. set: function (value) {
  21591. if (this._hasAlpha === value) {
  21592. return;
  21593. }
  21594. this._hasAlpha = value;
  21595. if (this._scene) {
  21596. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21597. }
  21598. },
  21599. enumerable: true,
  21600. configurable: true
  21601. });
  21602. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  21603. get: function () {
  21604. return this._coordinatesMode;
  21605. },
  21606. set: function (value) {
  21607. if (this._coordinatesMode === value) {
  21608. return;
  21609. }
  21610. this._coordinatesMode = value;
  21611. if (this._scene) {
  21612. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21613. }
  21614. },
  21615. enumerable: true,
  21616. configurable: true
  21617. });
  21618. Object.defineProperty(BaseTexture.prototype, "uid", {
  21619. get: function () {
  21620. if (!this._uid) {
  21621. this._uid = BABYLON.Tools.RandomId();
  21622. }
  21623. return this._uid;
  21624. },
  21625. enumerable: true,
  21626. configurable: true
  21627. });
  21628. BaseTexture.prototype.toString = function () {
  21629. return this.name;
  21630. };
  21631. BaseTexture.prototype.getClassName = function () {
  21632. return "BaseTexture";
  21633. };
  21634. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  21635. set: function (callback) {
  21636. if (this._onDisposeObserver) {
  21637. this.onDisposeObservable.remove(this._onDisposeObserver);
  21638. }
  21639. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21640. },
  21641. enumerable: true,
  21642. configurable: true
  21643. });
  21644. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  21645. get: function () {
  21646. return true;
  21647. },
  21648. enumerable: true,
  21649. configurable: true
  21650. });
  21651. BaseTexture.prototype.getScene = function () {
  21652. return this._scene;
  21653. };
  21654. BaseTexture.prototype.getTextureMatrix = function () {
  21655. return BABYLON.Matrix.IdentityReadOnly;
  21656. };
  21657. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  21658. return BABYLON.Matrix.IdentityReadOnly;
  21659. };
  21660. BaseTexture.prototype.getInternalTexture = function () {
  21661. return this._texture;
  21662. };
  21663. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  21664. return !this.isBlocking || this.isReady();
  21665. };
  21666. BaseTexture.prototype.isReady = function () {
  21667. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21668. this.delayLoad();
  21669. return false;
  21670. }
  21671. if (this._texture) {
  21672. return this._texture.isReady;
  21673. }
  21674. return false;
  21675. };
  21676. BaseTexture.prototype.getSize = function () {
  21677. if (this._texture && this._texture.width) {
  21678. return new BABYLON.Size(this._texture.width, this._texture.height);
  21679. }
  21680. if (this._texture && this._texture._size) {
  21681. return new BABYLON.Size(this._texture._size, this._texture._size);
  21682. }
  21683. return BABYLON.Size.Zero();
  21684. };
  21685. BaseTexture.prototype.getBaseSize = function () {
  21686. if (!this.isReady() || !this._texture)
  21687. return BABYLON.Size.Zero();
  21688. if (this._texture._size) {
  21689. return new BABYLON.Size(this._texture._size, this._texture._size);
  21690. }
  21691. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  21692. };
  21693. BaseTexture.prototype.scale = function (ratio) {
  21694. };
  21695. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  21696. get: function () {
  21697. return false;
  21698. },
  21699. enumerable: true,
  21700. configurable: true
  21701. });
  21702. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  21703. if (!this._scene) {
  21704. return null;
  21705. }
  21706. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  21707. for (var index = 0; index < texturesCache.length; index++) {
  21708. var texturesCacheEntry = texturesCache[index];
  21709. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  21710. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  21711. texturesCacheEntry.incrementReferences();
  21712. return texturesCacheEntry;
  21713. }
  21714. }
  21715. }
  21716. return null;
  21717. };
  21718. BaseTexture.prototype._rebuild = function () {
  21719. };
  21720. BaseTexture.prototype.delayLoad = function () {
  21721. };
  21722. BaseTexture.prototype.clone = function () {
  21723. return null;
  21724. };
  21725. Object.defineProperty(BaseTexture.prototype, "textureType", {
  21726. get: function () {
  21727. if (!this._texture) {
  21728. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21729. }
  21730. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  21731. },
  21732. enumerable: true,
  21733. configurable: true
  21734. });
  21735. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  21736. get: function () {
  21737. if (!this._texture) {
  21738. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21739. }
  21740. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. BaseTexture.prototype.readPixels = function (faceIndex) {
  21746. if (faceIndex === void 0) { faceIndex = 0; }
  21747. if (!this._texture) {
  21748. return null;
  21749. }
  21750. var size = this.getSize();
  21751. var scene = this.getScene();
  21752. if (!scene) {
  21753. return null;
  21754. }
  21755. var engine = scene.getEngine();
  21756. if (this._texture.isCube) {
  21757. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  21758. }
  21759. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  21760. };
  21761. BaseTexture.prototype.releaseInternalTexture = function () {
  21762. if (this._texture) {
  21763. this._texture.dispose();
  21764. this._texture = null;
  21765. }
  21766. };
  21767. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  21768. get: function () {
  21769. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  21770. return null;
  21771. }
  21772. if (!this._texture._sphericalPolynomial) {
  21773. this._texture._sphericalPolynomial =
  21774. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  21775. }
  21776. return this._texture._sphericalPolynomial;
  21777. },
  21778. set: function (value) {
  21779. if (this._texture) {
  21780. this._texture._sphericalPolynomial = value;
  21781. }
  21782. },
  21783. enumerable: true,
  21784. configurable: true
  21785. });
  21786. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  21787. get: function () {
  21788. if (this._texture) {
  21789. return this._texture._lodTextureHigh;
  21790. }
  21791. return null;
  21792. },
  21793. enumerable: true,
  21794. configurable: true
  21795. });
  21796. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  21797. get: function () {
  21798. if (this._texture) {
  21799. return this._texture._lodTextureMid;
  21800. }
  21801. return null;
  21802. },
  21803. enumerable: true,
  21804. configurable: true
  21805. });
  21806. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  21807. get: function () {
  21808. if (this._texture) {
  21809. return this._texture._lodTextureLow;
  21810. }
  21811. return null;
  21812. },
  21813. enumerable: true,
  21814. configurable: true
  21815. });
  21816. BaseTexture.prototype.dispose = function () {
  21817. if (!this._scene) {
  21818. return;
  21819. }
  21820. // Animations
  21821. this._scene.stopAnimation(this);
  21822. // Remove from scene
  21823. this._scene._removePendingData(this);
  21824. var index = this._scene.textures.indexOf(this);
  21825. if (index >= 0) {
  21826. this._scene.textures.splice(index, 1);
  21827. }
  21828. if (this._texture === undefined) {
  21829. return;
  21830. }
  21831. // Release
  21832. this.releaseInternalTexture();
  21833. // Callback
  21834. this.onDisposeObservable.notifyObservers(this);
  21835. this.onDisposeObservable.clear();
  21836. };
  21837. BaseTexture.prototype.serialize = function () {
  21838. if (!this.name) {
  21839. return null;
  21840. }
  21841. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21842. // Animations
  21843. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21844. return serializationObject;
  21845. };
  21846. BaseTexture.WhenAllReady = function (textures, callback) {
  21847. var numRemaining = textures.length;
  21848. if (numRemaining === 0) {
  21849. callback();
  21850. return;
  21851. }
  21852. var _loop_1 = function () {
  21853. texture = textures[i];
  21854. if (texture.isReady()) {
  21855. if (--numRemaining === 0) {
  21856. callback();
  21857. }
  21858. }
  21859. else {
  21860. onLoadObservable = texture.onLoadObservable;
  21861. var onLoadCallback_1 = function () {
  21862. onLoadObservable.removeCallback(onLoadCallback_1);
  21863. if (--numRemaining === 0) {
  21864. callback();
  21865. }
  21866. };
  21867. onLoadObservable.add(onLoadCallback_1);
  21868. }
  21869. };
  21870. var texture, onLoadObservable;
  21871. for (var i = 0; i < textures.length; i++) {
  21872. _loop_1();
  21873. }
  21874. };
  21875. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  21876. __decorate([
  21877. BABYLON.serialize()
  21878. ], BaseTexture.prototype, "name", void 0);
  21879. __decorate([
  21880. BABYLON.serialize("hasAlpha")
  21881. ], BaseTexture.prototype, "_hasAlpha", void 0);
  21882. __decorate([
  21883. BABYLON.serialize()
  21884. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  21885. __decorate([
  21886. BABYLON.serialize()
  21887. ], BaseTexture.prototype, "level", void 0);
  21888. __decorate([
  21889. BABYLON.serialize()
  21890. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  21891. __decorate([
  21892. BABYLON.serialize("coordinatesMode")
  21893. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  21894. __decorate([
  21895. BABYLON.serialize()
  21896. ], BaseTexture.prototype, "wrapU", void 0);
  21897. __decorate([
  21898. BABYLON.serialize()
  21899. ], BaseTexture.prototype, "wrapV", void 0);
  21900. __decorate([
  21901. BABYLON.serialize()
  21902. ], BaseTexture.prototype, "wrapR", void 0);
  21903. __decorate([
  21904. BABYLON.serialize()
  21905. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  21906. __decorate([
  21907. BABYLON.serialize()
  21908. ], BaseTexture.prototype, "isCube", void 0);
  21909. __decorate([
  21910. BABYLON.serialize()
  21911. ], BaseTexture.prototype, "is3D", void 0);
  21912. __decorate([
  21913. BABYLON.serialize()
  21914. ], BaseTexture.prototype, "gammaSpace", void 0);
  21915. __decorate([
  21916. BABYLON.serialize()
  21917. ], BaseTexture.prototype, "invertZ", void 0);
  21918. __decorate([
  21919. BABYLON.serialize()
  21920. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  21921. __decorate([
  21922. BABYLON.serialize()
  21923. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  21924. __decorate([
  21925. BABYLON.serialize()
  21926. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  21927. __decorate([
  21928. BABYLON.serialize()
  21929. ], BaseTexture.prototype, "isRenderTarget", void 0);
  21930. return BaseTexture;
  21931. }());
  21932. BABYLON.BaseTexture = BaseTexture;
  21933. })(BABYLON || (BABYLON = {}));
  21934. //# sourceMappingURL=babylon.baseTexture.js.map
  21935. var BABYLON;
  21936. (function (BABYLON) {
  21937. var Texture = /** @class */ (function (_super) {
  21938. __extends(Texture, _super);
  21939. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  21940. if (noMipmap === void 0) { noMipmap = false; }
  21941. if (invertY === void 0) { invertY = true; }
  21942. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  21943. if (onLoad === void 0) { onLoad = null; }
  21944. if (onError === void 0) { onError = null; }
  21945. if (buffer === void 0) { buffer = null; }
  21946. if (deleteBuffer === void 0) { deleteBuffer = false; }
  21947. var _this = _super.call(this, scene) || this;
  21948. _this.uOffset = 0;
  21949. _this.vOffset = 0;
  21950. _this.uScale = 1.0;
  21951. _this.vScale = 1.0;
  21952. _this.uAng = 0;
  21953. _this.vAng = 0;
  21954. _this.wAng = 0;
  21955. _this._isBlocking = true;
  21956. _this.name = url || "";
  21957. _this.url = url;
  21958. _this._noMipmap = noMipmap;
  21959. _this._invertY = invertY;
  21960. _this._samplingMode = samplingMode;
  21961. _this._buffer = buffer;
  21962. _this._deleteBuffer = deleteBuffer;
  21963. if (format) {
  21964. _this._format = format;
  21965. }
  21966. scene = _this.getScene();
  21967. if (!scene) {
  21968. return _this;
  21969. }
  21970. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  21971. var load = function () {
  21972. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  21973. _this.onLoadObservable.notifyObservers(_this);
  21974. }
  21975. if (onLoad) {
  21976. onLoad();
  21977. }
  21978. if (!_this.isBlocking && scene) {
  21979. scene.resetCachedMaterial();
  21980. }
  21981. };
  21982. if (!_this.url) {
  21983. _this._delayedOnLoad = load;
  21984. _this._delayedOnError = onError;
  21985. return _this;
  21986. }
  21987. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  21988. if (!_this._texture) {
  21989. if (!scene.useDelayedTextureLoading) {
  21990. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  21991. if (deleteBuffer) {
  21992. delete _this._buffer;
  21993. }
  21994. }
  21995. else {
  21996. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21997. _this._delayedOnLoad = load;
  21998. _this._delayedOnError = onError;
  21999. }
  22000. }
  22001. else {
  22002. if (_this._texture.isReady) {
  22003. BABYLON.Tools.SetImmediate(function () { return load(); });
  22004. }
  22005. else {
  22006. _this._texture.onLoadedObservable.add(load);
  22007. }
  22008. }
  22009. return _this;
  22010. }
  22011. Object.defineProperty(Texture.prototype, "noMipmap", {
  22012. get: function () {
  22013. return this._noMipmap;
  22014. },
  22015. enumerable: true,
  22016. configurable: true
  22017. });
  22018. Object.defineProperty(Texture.prototype, "isBlocking", {
  22019. get: function () {
  22020. return this._isBlocking;
  22021. },
  22022. set: function (value) {
  22023. this._isBlocking = value;
  22024. },
  22025. enumerable: true,
  22026. configurable: true
  22027. });
  22028. Object.defineProperty(Texture.prototype, "samplingMode", {
  22029. get: function () {
  22030. return this._samplingMode;
  22031. },
  22032. enumerable: true,
  22033. configurable: true
  22034. });
  22035. Texture.prototype.updateURL = function (url) {
  22036. this.url = url;
  22037. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22038. this.delayLoad();
  22039. };
  22040. Texture.prototype.delayLoad = function () {
  22041. var _this = this;
  22042. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22043. return;
  22044. }
  22045. var scene = this.getScene();
  22046. if (!scene) {
  22047. return;
  22048. }
  22049. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22050. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22051. if (!this._texture) {
  22052. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  22053. if (this._deleteBuffer) {
  22054. delete this._buffer;
  22055. }
  22056. }
  22057. else {
  22058. if (this._texture.isReady) {
  22059. BABYLON.Tools.SetImmediate(function () {
  22060. if (!_this._delayedOnLoad) {
  22061. return;
  22062. }
  22063. _this._delayedOnLoad();
  22064. });
  22065. }
  22066. else {
  22067. if (this._delayedOnLoad) {
  22068. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  22069. }
  22070. }
  22071. }
  22072. };
  22073. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22074. if (!this._texture) {
  22075. return;
  22076. }
  22077. var scene = this.getScene();
  22078. if (!scene) {
  22079. return;
  22080. }
  22081. this._samplingMode = samplingMode;
  22082. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22083. };
  22084. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22085. x *= this.uScale;
  22086. y *= this.vScale;
  22087. x -= 0.5 * this.uScale;
  22088. y -= 0.5 * this.vScale;
  22089. z -= 0.5;
  22090. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22091. t.x += 0.5 * this.uScale + this.uOffset;
  22092. t.y += 0.5 * this.vScale + this.vOffset;
  22093. t.z += 0.5;
  22094. };
  22095. Texture.prototype.getTextureMatrix = function () {
  22096. var _this = this;
  22097. if (this.uOffset === this._cachedUOffset &&
  22098. this.vOffset === this._cachedVOffset &&
  22099. this.uScale === this._cachedUScale &&
  22100. this.vScale === this._cachedVScale &&
  22101. this.uAng === this._cachedUAng &&
  22102. this.vAng === this._cachedVAng &&
  22103. this.wAng === this._cachedWAng) {
  22104. return this._cachedTextureMatrix;
  22105. }
  22106. this._cachedUOffset = this.uOffset;
  22107. this._cachedVOffset = this.vOffset;
  22108. this._cachedUScale = this.uScale;
  22109. this._cachedVScale = this.vScale;
  22110. this._cachedUAng = this.uAng;
  22111. this._cachedVAng = this.vAng;
  22112. this._cachedWAng = this.wAng;
  22113. if (!this._cachedTextureMatrix) {
  22114. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22115. this._rowGenerationMatrix = new BABYLON.Matrix();
  22116. this._t0 = BABYLON.Vector3.Zero();
  22117. this._t1 = BABYLON.Vector3.Zero();
  22118. this._t2 = BABYLON.Vector3.Zero();
  22119. }
  22120. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22121. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22122. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22123. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22124. this._t1.subtractInPlace(this._t0);
  22125. this._t2.subtractInPlace(this._t0);
  22126. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22127. this._cachedTextureMatrix.m[0] = this._t1.x;
  22128. this._cachedTextureMatrix.m[1] = this._t1.y;
  22129. this._cachedTextureMatrix.m[2] = this._t1.z;
  22130. this._cachedTextureMatrix.m[4] = this._t2.x;
  22131. this._cachedTextureMatrix.m[5] = this._t2.y;
  22132. this._cachedTextureMatrix.m[6] = this._t2.z;
  22133. this._cachedTextureMatrix.m[8] = this._t0.x;
  22134. this._cachedTextureMatrix.m[9] = this._t0.y;
  22135. this._cachedTextureMatrix.m[10] = this._t0.z;
  22136. var scene = this.getScene();
  22137. if (!scene) {
  22138. return this._cachedTextureMatrix;
  22139. }
  22140. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22141. return mat.hasTexture(_this);
  22142. });
  22143. return this._cachedTextureMatrix;
  22144. };
  22145. Texture.prototype.getReflectionTextureMatrix = function () {
  22146. var _this = this;
  22147. var scene = this.getScene();
  22148. if (!scene) {
  22149. return this._cachedTextureMatrix;
  22150. }
  22151. if (this.uOffset === this._cachedUOffset &&
  22152. this.vOffset === this._cachedVOffset &&
  22153. this.uScale === this._cachedUScale &&
  22154. this.vScale === this._cachedVScale &&
  22155. this.coordinatesMode === this._cachedCoordinatesMode) {
  22156. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  22157. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  22158. return this._cachedTextureMatrix;
  22159. }
  22160. }
  22161. else {
  22162. return this._cachedTextureMatrix;
  22163. }
  22164. }
  22165. if (!this._cachedTextureMatrix) {
  22166. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22167. }
  22168. if (!this._projectionModeMatrix) {
  22169. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22170. }
  22171. this._cachedUOffset = this.uOffset;
  22172. this._cachedVOffset = this.vOffset;
  22173. this._cachedUScale = this.uScale;
  22174. this._cachedVScale = this.vScale;
  22175. this._cachedCoordinatesMode = this.coordinatesMode;
  22176. switch (this.coordinatesMode) {
  22177. case Texture.PLANAR_MODE:
  22178. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22179. this._cachedTextureMatrix[0] = this.uScale;
  22180. this._cachedTextureMatrix[5] = this.vScale;
  22181. this._cachedTextureMatrix[12] = this.uOffset;
  22182. this._cachedTextureMatrix[13] = this.vOffset;
  22183. break;
  22184. case Texture.PROJECTION_MODE:
  22185. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22186. this._projectionModeMatrix.m[0] = 0.5;
  22187. this._projectionModeMatrix.m[5] = -0.5;
  22188. this._projectionModeMatrix.m[10] = 0.0;
  22189. this._projectionModeMatrix.m[12] = 0.5;
  22190. this._projectionModeMatrix.m[13] = 0.5;
  22191. this._projectionModeMatrix.m[14] = 1.0;
  22192. this._projectionModeMatrix.m[15] = 1.0;
  22193. var projectionMatrix = scene.getProjectionMatrix();
  22194. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  22195. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22196. break;
  22197. default:
  22198. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22199. break;
  22200. }
  22201. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  22202. return (mat.getActiveTextures().indexOf(_this) !== -1);
  22203. });
  22204. return this._cachedTextureMatrix;
  22205. };
  22206. Texture.prototype.clone = function () {
  22207. var _this = this;
  22208. return BABYLON.SerializationHelper.Clone(function () {
  22209. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22210. }, this);
  22211. };
  22212. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22213. get: function () {
  22214. if (!this._onLoadObservable) {
  22215. this._onLoadObservable = new BABYLON.Observable();
  22216. }
  22217. return this._onLoadObservable;
  22218. },
  22219. enumerable: true,
  22220. configurable: true
  22221. });
  22222. Texture.prototype.serialize = function () {
  22223. var serializationObject = _super.prototype.serialize.call(this);
  22224. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  22225. serializationObject.base64String = this._buffer;
  22226. serializationObject.name = serializationObject.name.replace("data:", "");
  22227. }
  22228. return serializationObject;
  22229. };
  22230. Texture.prototype.getClassName = function () {
  22231. return "Texture";
  22232. };
  22233. Texture.prototype.dispose = function () {
  22234. _super.prototype.dispose.call(this);
  22235. if (this.onLoadObservable) {
  22236. this.onLoadObservable.clear();
  22237. this._onLoadObservable = null;
  22238. }
  22239. this._delayedOnLoad = null;
  22240. this._delayedOnError = null;
  22241. };
  22242. // Statics
  22243. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22244. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22245. if (onLoad === void 0) { onLoad = null; }
  22246. if (onError === void 0) { onError = null; }
  22247. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22248. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  22249. };
  22250. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22251. if (parsedTexture.customType) {
  22252. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22253. // Update Sampling Mode
  22254. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  22255. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  22256. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  22257. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  22258. }
  22259. }
  22260. return parsedCustomTexture;
  22261. }
  22262. if (parsedTexture.isCube) {
  22263. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22264. }
  22265. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22266. return null;
  22267. }
  22268. var texture = BABYLON.SerializationHelper.Parse(function () {
  22269. if (parsedTexture.mirrorPlane) {
  22270. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22271. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22272. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22273. return mirrorTexture;
  22274. }
  22275. else if (parsedTexture.isRenderTarget) {
  22276. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22277. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22278. return renderTargetTexture;
  22279. }
  22280. else {
  22281. var texture;
  22282. if (parsedTexture.base64String) {
  22283. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22284. }
  22285. else {
  22286. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22287. }
  22288. return texture;
  22289. }
  22290. }, parsedTexture, scene);
  22291. // Update Sampling Mode
  22292. if (parsedTexture.samplingMode) {
  22293. var sampling = parsedTexture.samplingMode;
  22294. if (texture._samplingMode !== sampling) {
  22295. texture.updateSamplingMode(sampling);
  22296. }
  22297. }
  22298. // Animations
  22299. if (parsedTexture.animations) {
  22300. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22301. var parsedAnimation = parsedTexture.animations[animationIndex];
  22302. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22303. }
  22304. }
  22305. return texture;
  22306. };
  22307. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  22308. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22309. if (noMipmap === void 0) { noMipmap = false; }
  22310. if (invertY === void 0) { invertY = true; }
  22311. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22312. if (onLoad === void 0) { onLoad = null; }
  22313. if (onError === void 0) { onError = null; }
  22314. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  22315. if (name.substr(0, 5) !== "data:") {
  22316. name = "data:" + name;
  22317. }
  22318. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  22319. };
  22320. // Constants
  22321. Texture.NEAREST_SAMPLINGMODE = 1;
  22322. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  22323. Texture.BILINEAR_SAMPLINGMODE = 2;
  22324. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  22325. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22326. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  22327. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  22328. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  22329. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  22330. Texture.NEAREST_LINEAR = 7;
  22331. Texture.NEAREST_NEAREST = 8;
  22332. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  22333. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  22334. Texture.LINEAR_LINEAR = 11;
  22335. Texture.LINEAR_NEAREST = 12;
  22336. Texture.EXPLICIT_MODE = 0;
  22337. Texture.SPHERICAL_MODE = 1;
  22338. Texture.PLANAR_MODE = 2;
  22339. Texture.CUBIC_MODE = 3;
  22340. Texture.PROJECTION_MODE = 4;
  22341. Texture.SKYBOX_MODE = 5;
  22342. Texture.INVCUBIC_MODE = 6;
  22343. Texture.EQUIRECTANGULAR_MODE = 7;
  22344. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22345. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  22346. Texture.CLAMP_ADDRESSMODE = 0;
  22347. Texture.WRAP_ADDRESSMODE = 1;
  22348. Texture.MIRROR_ADDRESSMODE = 2;
  22349. __decorate([
  22350. BABYLON.serialize()
  22351. ], Texture.prototype, "url", void 0);
  22352. __decorate([
  22353. BABYLON.serialize()
  22354. ], Texture.prototype, "uOffset", void 0);
  22355. __decorate([
  22356. BABYLON.serialize()
  22357. ], Texture.prototype, "vOffset", void 0);
  22358. __decorate([
  22359. BABYLON.serialize()
  22360. ], Texture.prototype, "uScale", void 0);
  22361. __decorate([
  22362. BABYLON.serialize()
  22363. ], Texture.prototype, "vScale", void 0);
  22364. __decorate([
  22365. BABYLON.serialize()
  22366. ], Texture.prototype, "uAng", void 0);
  22367. __decorate([
  22368. BABYLON.serialize()
  22369. ], Texture.prototype, "vAng", void 0);
  22370. __decorate([
  22371. BABYLON.serialize()
  22372. ], Texture.prototype, "wAng", void 0);
  22373. __decorate([
  22374. BABYLON.serialize()
  22375. ], Texture.prototype, "isBlocking", null);
  22376. return Texture;
  22377. }(BABYLON.BaseTexture));
  22378. BABYLON.Texture = Texture;
  22379. })(BABYLON || (BABYLON = {}));
  22380. //# sourceMappingURL=babylon.texture.js.map
  22381. var BABYLON;
  22382. (function (BABYLON) {
  22383. var _InstancesBatch = /** @class */ (function () {
  22384. function _InstancesBatch() {
  22385. this.mustReturn = false;
  22386. this.visibleInstances = new Array();
  22387. this.renderSelf = new Array();
  22388. }
  22389. return _InstancesBatch;
  22390. }());
  22391. BABYLON._InstancesBatch = _InstancesBatch;
  22392. var Mesh = /** @class */ (function (_super) {
  22393. __extends(Mesh, _super);
  22394. /**
  22395. * @constructor
  22396. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  22397. * @param {Scene} scene The scene to add this mesh to.
  22398. * @param {Node} parent The parent of this mesh, if it has one
  22399. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  22400. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  22401. * When false, achieved by calling a clone(), also passing False.
  22402. * This will make creation of children, recursive.
  22403. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  22404. */
  22405. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  22406. if (scene === void 0) { scene = null; }
  22407. if (parent === void 0) { parent = null; }
  22408. if (source === void 0) { source = null; }
  22409. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22410. var _this = _super.call(this, name, scene) || this;
  22411. // Events
  22412. /**
  22413. * An event triggered before rendering the mesh
  22414. * @type {BABYLON.Observable}
  22415. */
  22416. _this.onBeforeRenderObservable = new BABYLON.Observable();
  22417. /**
  22418. * An event triggered after rendering the mesh
  22419. * @type {BABYLON.Observable}
  22420. */
  22421. _this.onAfterRenderObservable = new BABYLON.Observable();
  22422. /**
  22423. * An event triggered before drawing the mesh
  22424. * @type {BABYLON.Observable}
  22425. */
  22426. _this.onBeforeDrawObservable = new BABYLON.Observable();
  22427. // Members
  22428. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22429. _this.instances = new Array();
  22430. _this._LODLevels = new Array();
  22431. _this._visibleInstances = {};
  22432. _this._renderIdForInstances = new Array();
  22433. _this._batchCache = new _InstancesBatch();
  22434. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  22435. // Use by builder only to know what orientation were the mesh build in.
  22436. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  22437. _this.overrideMaterialSideOrientation = null;
  22438. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  22439. // Will be used to save a source mesh reference, If any
  22440. _this._source = null;
  22441. scene = _this.getScene();
  22442. if (source) {
  22443. // Source mesh
  22444. _this._source = source;
  22445. // Geometry
  22446. if (source._geometry) {
  22447. source._geometry.applyToMesh(_this);
  22448. }
  22449. // Deep copy
  22450. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  22451. // Tags
  22452. if (BABYLON.Tags.HasTags(source)) {
  22453. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  22454. }
  22455. _this.metadata = source.metadata;
  22456. // Parent
  22457. _this.parent = source.parent;
  22458. // Pivot
  22459. _this.setPivotMatrix(source.getPivotMatrix());
  22460. _this.id = name + "." + source.id;
  22461. // Material
  22462. _this.material = source.material;
  22463. var index;
  22464. if (!doNotCloneChildren) {
  22465. // Children
  22466. for (index = 0; index < scene.meshes.length; index++) {
  22467. var mesh = scene.meshes[index];
  22468. if (mesh.parent === source) {
  22469. // doNotCloneChildren is always going to be False
  22470. mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  22471. }
  22472. }
  22473. }
  22474. // Physics clone
  22475. var physicsEngine = _this.getScene().getPhysicsEngine();
  22476. if (clonePhysicsImpostor && physicsEngine) {
  22477. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  22478. if (impostor) {
  22479. _this.physicsImpostor = impostor.clone(_this);
  22480. }
  22481. }
  22482. // Particles
  22483. for (index = 0; index < scene.particleSystems.length; index++) {
  22484. var system = scene.particleSystems[index];
  22485. if (system.emitter === source) {
  22486. system.clone(system.name, _this);
  22487. }
  22488. }
  22489. _this.computeWorldMatrix(true);
  22490. }
  22491. // Parent
  22492. if (parent !== null) {
  22493. _this.parent = parent;
  22494. }
  22495. return _this;
  22496. }
  22497. Object.defineProperty(Mesh, "FRONTSIDE", {
  22498. /**
  22499. * Mesh side orientation : usually the external or front surface
  22500. */
  22501. get: function () {
  22502. return Mesh._FRONTSIDE;
  22503. },
  22504. enumerable: true,
  22505. configurable: true
  22506. });
  22507. Object.defineProperty(Mesh, "BACKSIDE", {
  22508. /**
  22509. * Mesh side orientation : usually the internal or back surface
  22510. */
  22511. get: function () {
  22512. return Mesh._BACKSIDE;
  22513. },
  22514. enumerable: true,
  22515. configurable: true
  22516. });
  22517. Object.defineProperty(Mesh, "DOUBLESIDE", {
  22518. /**
  22519. * Mesh side orientation : both internal and external or front and back surfaces
  22520. */
  22521. get: function () {
  22522. return Mesh._DOUBLESIDE;
  22523. },
  22524. enumerable: true,
  22525. configurable: true
  22526. });
  22527. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  22528. /**
  22529. * Mesh side orientation : by default, `FRONTSIDE`
  22530. */
  22531. get: function () {
  22532. return Mesh._DEFAULTSIDE;
  22533. },
  22534. enumerable: true,
  22535. configurable: true
  22536. });
  22537. Object.defineProperty(Mesh, "NO_CAP", {
  22538. /**
  22539. * Mesh cap setting : no cap
  22540. */
  22541. get: function () {
  22542. return Mesh._NO_CAP;
  22543. },
  22544. enumerable: true,
  22545. configurable: true
  22546. });
  22547. Object.defineProperty(Mesh, "CAP_START", {
  22548. /**
  22549. * Mesh cap setting : one cap at the beginning of the mesh
  22550. */
  22551. get: function () {
  22552. return Mesh._CAP_START;
  22553. },
  22554. enumerable: true,
  22555. configurable: true
  22556. });
  22557. Object.defineProperty(Mesh, "CAP_END", {
  22558. /**
  22559. * Mesh cap setting : one cap at the end of the mesh
  22560. */
  22561. get: function () {
  22562. return Mesh._CAP_END;
  22563. },
  22564. enumerable: true,
  22565. configurable: true
  22566. });
  22567. Object.defineProperty(Mesh, "CAP_ALL", {
  22568. /**
  22569. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  22570. */
  22571. get: function () {
  22572. return Mesh._CAP_ALL;
  22573. },
  22574. enumerable: true,
  22575. configurable: true
  22576. });
  22577. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  22578. set: function (callback) {
  22579. if (this._onBeforeDrawObserver) {
  22580. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  22581. }
  22582. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  22583. },
  22584. enumerable: true,
  22585. configurable: true
  22586. });
  22587. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  22588. get: function () {
  22589. return this._morphTargetManager;
  22590. },
  22591. set: function (value) {
  22592. if (this._morphTargetManager === value) {
  22593. return;
  22594. }
  22595. this._morphTargetManager = value;
  22596. this._syncGeometryWithMorphTargetManager();
  22597. },
  22598. enumerable: true,
  22599. configurable: true
  22600. });
  22601. Object.defineProperty(Mesh.prototype, "source", {
  22602. get: function () {
  22603. return this._source;
  22604. },
  22605. enumerable: true,
  22606. configurable: true
  22607. });
  22608. // Methods
  22609. /**
  22610. * Returns the string "Mesh".
  22611. */
  22612. Mesh.prototype.getClassName = function () {
  22613. return "Mesh";
  22614. };
  22615. /**
  22616. * Returns a string.
  22617. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22618. */
  22619. Mesh.prototype.toString = function (fullDetails) {
  22620. var ret = _super.prototype.toString.call(this, fullDetails);
  22621. ret += ", n vertices: " + this.getTotalVertices();
  22622. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  22623. if (this.animations) {
  22624. for (var i = 0; i < this.animations.length; i++) {
  22625. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22626. }
  22627. }
  22628. if (fullDetails) {
  22629. if (this._geometry) {
  22630. var ib = this.getIndices();
  22631. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22632. if (vb && ib) {
  22633. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  22634. }
  22635. }
  22636. else {
  22637. ret += ", flat shading: UNKNOWN";
  22638. }
  22639. }
  22640. return ret;
  22641. };
  22642. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  22643. /**
  22644. * True if the mesh has some Levels Of Details (LOD).
  22645. * Returns a boolean.
  22646. */
  22647. get: function () {
  22648. return this._LODLevels.length > 0;
  22649. },
  22650. enumerable: true,
  22651. configurable: true
  22652. });
  22653. Mesh.prototype._sortLODLevels = function () {
  22654. this._LODLevels.sort(function (a, b) {
  22655. if (a.distance < b.distance) {
  22656. return 1;
  22657. }
  22658. if (a.distance > b.distance) {
  22659. return -1;
  22660. }
  22661. return 0;
  22662. });
  22663. };
  22664. /**
  22665. * Add a mesh as LOD level triggered at the given distance.
  22666. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22667. * @param {number} distance The distance from the center of the object to show this level
  22668. * @param {Mesh} mesh The mesh to be added as LOD level
  22669. * @return {Mesh} This mesh (for chaining)
  22670. */
  22671. Mesh.prototype.addLODLevel = function (distance, mesh) {
  22672. if (mesh && mesh._masterMesh) {
  22673. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  22674. return this;
  22675. }
  22676. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  22677. this._LODLevels.push(level);
  22678. if (mesh) {
  22679. mesh._masterMesh = this;
  22680. }
  22681. this._sortLODLevels();
  22682. return this;
  22683. };
  22684. /**
  22685. * Returns the LOD level mesh at the passed distance or null if not found.
  22686. * It is related to the method `addLODLevel(distance, mesh)`.
  22687. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22688. * Returns an object Mesh or `null`.
  22689. */
  22690. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  22691. for (var index = 0; index < this._LODLevels.length; index++) {
  22692. var level = this._LODLevels[index];
  22693. if (level.distance === distance) {
  22694. return level.mesh;
  22695. }
  22696. }
  22697. return null;
  22698. };
  22699. /**
  22700. * Remove a mesh from the LOD array
  22701. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22702. * @param {Mesh} mesh The mesh to be removed.
  22703. * @return {Mesh} This mesh (for chaining)
  22704. */
  22705. Mesh.prototype.removeLODLevel = function (mesh) {
  22706. for (var index = 0; index < this._LODLevels.length; index++) {
  22707. if (this._LODLevels[index].mesh === mesh) {
  22708. this._LODLevels.splice(index, 1);
  22709. if (mesh) {
  22710. mesh._masterMesh = null;
  22711. }
  22712. }
  22713. }
  22714. this._sortLODLevels();
  22715. return this;
  22716. };
  22717. /**
  22718. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  22719. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  22720. */
  22721. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  22722. if (!this._LODLevels || this._LODLevels.length === 0) {
  22723. return this;
  22724. }
  22725. var bSphere;
  22726. if (boundingSphere) {
  22727. bSphere = boundingSphere;
  22728. }
  22729. else {
  22730. var boundingInfo = this.getBoundingInfo();
  22731. if (!boundingInfo) {
  22732. return this;
  22733. }
  22734. bSphere = boundingInfo.boundingSphere;
  22735. }
  22736. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  22737. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  22738. if (this.onLODLevelSelection) {
  22739. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  22740. }
  22741. return this;
  22742. }
  22743. for (var index = 0; index < this._LODLevels.length; index++) {
  22744. var level = this._LODLevels[index];
  22745. if (level.distance < distanceToCamera) {
  22746. if (level.mesh) {
  22747. level.mesh._preActivate();
  22748. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  22749. }
  22750. if (this.onLODLevelSelection) {
  22751. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  22752. }
  22753. return level.mesh;
  22754. }
  22755. }
  22756. if (this.onLODLevelSelection) {
  22757. this.onLODLevelSelection(distanceToCamera, this, this);
  22758. }
  22759. return this;
  22760. };
  22761. Object.defineProperty(Mesh.prototype, "geometry", {
  22762. /**
  22763. * Returns the mesh internal Geometry object.
  22764. */
  22765. get: function () {
  22766. return this._geometry;
  22767. },
  22768. enumerable: true,
  22769. configurable: true
  22770. });
  22771. /**
  22772. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  22773. */
  22774. Mesh.prototype.getTotalVertices = function () {
  22775. if (!this._geometry) {
  22776. return 0;
  22777. }
  22778. return this._geometry.getTotalVertices();
  22779. };
  22780. /**
  22781. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  22782. * 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.
  22783. * You can force the copy with forceCopy === true
  22784. * Returns null if the mesh has no geometry or no vertex buffer.
  22785. * Possible `kind` values :
  22786. * - BABYLON.VertexBuffer.PositionKind
  22787. * - BABYLON.VertexBuffer.UVKind
  22788. * - BABYLON.VertexBuffer.UV2Kind
  22789. * - BABYLON.VertexBuffer.UV3Kind
  22790. * - BABYLON.VertexBuffer.UV4Kind
  22791. * - BABYLON.VertexBuffer.UV5Kind
  22792. * - BABYLON.VertexBuffer.UV6Kind
  22793. * - BABYLON.VertexBuffer.ColorKind
  22794. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22795. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22796. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22797. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22798. */
  22799. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  22800. if (!this._geometry) {
  22801. return null;
  22802. }
  22803. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  22804. };
  22805. /**
  22806. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  22807. * Returns `null` if the mesh has no geometry.
  22808. * Possible `kind` values :
  22809. * - BABYLON.VertexBuffer.PositionKind
  22810. * - BABYLON.VertexBuffer.UVKind
  22811. * - BABYLON.VertexBuffer.UV2Kind
  22812. * - BABYLON.VertexBuffer.UV3Kind
  22813. * - BABYLON.VertexBuffer.UV4Kind
  22814. * - BABYLON.VertexBuffer.UV5Kind
  22815. * - BABYLON.VertexBuffer.UV6Kind
  22816. * - BABYLON.VertexBuffer.ColorKind
  22817. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22818. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22819. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22820. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22821. */
  22822. Mesh.prototype.getVertexBuffer = function (kind) {
  22823. if (!this._geometry) {
  22824. return null;
  22825. }
  22826. return this._geometry.getVertexBuffer(kind);
  22827. };
  22828. /**
  22829. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  22830. * Possible `kind` values :
  22831. * - BABYLON.VertexBuffer.PositionKind
  22832. * - BABYLON.VertexBuffer.UVKind
  22833. * - BABYLON.VertexBuffer.UV2Kind
  22834. * - BABYLON.VertexBuffer.UV3Kind
  22835. * - BABYLON.VertexBuffer.UV4Kind
  22836. * - BABYLON.VertexBuffer.UV5Kind
  22837. * - BABYLON.VertexBuffer.UV6Kind
  22838. * - BABYLON.VertexBuffer.ColorKind
  22839. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22840. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22841. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22842. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22843. */
  22844. Mesh.prototype.isVerticesDataPresent = function (kind) {
  22845. if (!this._geometry) {
  22846. if (this._delayInfo) {
  22847. return this._delayInfo.indexOf(kind) !== -1;
  22848. }
  22849. return false;
  22850. }
  22851. return this._geometry.isVerticesDataPresent(kind);
  22852. };
  22853. /**
  22854. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  22855. * Possible `kind` values :
  22856. * - BABYLON.VertexBuffer.PositionKind
  22857. * - BABYLON.VertexBuffer.UVKind
  22858. * - BABYLON.VertexBuffer.UV2Kind
  22859. * - BABYLON.VertexBuffer.UV3Kind
  22860. * - BABYLON.VertexBuffer.UV4Kind
  22861. * - BABYLON.VertexBuffer.UV5Kind
  22862. * - BABYLON.VertexBuffer.UV6Kind
  22863. * - BABYLON.VertexBuffer.ColorKind
  22864. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22865. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22866. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22867. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22868. */
  22869. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  22870. if (!this._geometry) {
  22871. if (this._delayInfo) {
  22872. return this._delayInfo.indexOf(kind) !== -1;
  22873. }
  22874. return false;
  22875. }
  22876. return this._geometry.isVertexBufferUpdatable(kind);
  22877. };
  22878. /**
  22879. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  22880. * Possible `kind` values :
  22881. * - BABYLON.VertexBuffer.PositionKind
  22882. * - BABYLON.VertexBuffer.UVKind
  22883. * - BABYLON.VertexBuffer.UV2Kind
  22884. * - BABYLON.VertexBuffer.UV3Kind
  22885. * - BABYLON.VertexBuffer.UV4Kind
  22886. * - BABYLON.VertexBuffer.UV5Kind
  22887. * - BABYLON.VertexBuffer.UV6Kind
  22888. * - BABYLON.VertexBuffer.ColorKind
  22889. * - BABYLON.VertexBuffer.MatricesIndicesKind
  22890. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  22891. * - BABYLON.VertexBuffer.MatricesWeightsKind
  22892. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  22893. */
  22894. Mesh.prototype.getVerticesDataKinds = function () {
  22895. if (!this._geometry) {
  22896. var result = new Array();
  22897. if (this._delayInfo) {
  22898. this._delayInfo.forEach(function (kind, index, array) {
  22899. result.push(kind);
  22900. });
  22901. }
  22902. return result;
  22903. }
  22904. return this._geometry.getVerticesDataKinds();
  22905. };
  22906. /**
  22907. * Returns a positive integer : the total number of indices in this mesh geometry.
  22908. * Returns zero if the mesh has no geometry.
  22909. */
  22910. Mesh.prototype.getTotalIndices = function () {
  22911. if (!this._geometry) {
  22912. return 0;
  22913. }
  22914. return this._geometry.getTotalIndices();
  22915. };
  22916. /**
  22917. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  22918. * 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.
  22919. * Returns an empty array if the mesh has no geometry.
  22920. */
  22921. Mesh.prototype.getIndices = function (copyWhenShared) {
  22922. if (!this._geometry) {
  22923. return [];
  22924. }
  22925. return this._geometry.getIndices(copyWhenShared);
  22926. };
  22927. Object.defineProperty(Mesh.prototype, "isBlocked", {
  22928. get: function () {
  22929. return this._masterMesh !== null && this._masterMesh !== undefined;
  22930. },
  22931. enumerable: true,
  22932. configurable: true
  22933. });
  22934. /**
  22935. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  22936. */
  22937. Mesh.prototype.isReady = function () {
  22938. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22939. return false;
  22940. }
  22941. return _super.prototype.isReady.call(this);
  22942. };
  22943. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  22944. /**
  22945. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  22946. * This property is pertinent only for updatable parametric shapes.
  22947. */
  22948. get: function () {
  22949. return this._areNormalsFrozen;
  22950. },
  22951. enumerable: true,
  22952. configurable: true
  22953. });
  22954. /**
  22955. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22956. * It has no effect at all on other shapes.
  22957. * It prevents the mesh normals from being recomputed on next `positions` array update.
  22958. * Returns the Mesh.
  22959. */
  22960. Mesh.prototype.freezeNormals = function () {
  22961. this._areNormalsFrozen = true;
  22962. return this;
  22963. };
  22964. /**
  22965. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  22966. * It has no effect at all on other shapes.
  22967. * It reactivates the mesh normals computation if it was previously frozen.
  22968. * Returns the Mesh.
  22969. */
  22970. Mesh.prototype.unfreezeNormals = function () {
  22971. this._areNormalsFrozen = false;
  22972. return this;
  22973. };
  22974. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  22975. /**
  22976. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  22977. */
  22978. set: function (count) {
  22979. this._overridenInstanceCount = count;
  22980. },
  22981. enumerable: true,
  22982. configurable: true
  22983. });
  22984. // Methods
  22985. Mesh.prototype._preActivate = function () {
  22986. var sceneRenderId = this.getScene().getRenderId();
  22987. if (this._preActivateId === sceneRenderId) {
  22988. return this;
  22989. }
  22990. this._preActivateId = sceneRenderId;
  22991. this._visibleInstances = null;
  22992. return this;
  22993. };
  22994. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  22995. if (this._visibleInstances) {
  22996. this._visibleInstances.intermediateDefaultRenderId = renderId;
  22997. }
  22998. return this;
  22999. };
  23000. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  23001. if (!this._visibleInstances) {
  23002. this._visibleInstances = {};
  23003. this._visibleInstances.defaultRenderId = renderId;
  23004. this._visibleInstances.selfDefaultRenderId = this._renderId;
  23005. }
  23006. if (!this._visibleInstances[renderId]) {
  23007. this._visibleInstances[renderId] = new Array();
  23008. }
  23009. this._visibleInstances[renderId].push(instance);
  23010. return this;
  23011. };
  23012. /**
  23013. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  23014. * This means the mesh underlying bounding box and sphere are recomputed.
  23015. * Returns the Mesh.
  23016. */
  23017. Mesh.prototype.refreshBoundingInfo = function () {
  23018. if (this._boundingInfo && this._boundingInfo.isLocked) {
  23019. return this;
  23020. }
  23021. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23022. if (data) {
  23023. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  23024. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23025. }
  23026. if (this.subMeshes) {
  23027. for (var index = 0; index < this.subMeshes.length; index++) {
  23028. this.subMeshes[index].refreshBoundingInfo();
  23029. }
  23030. }
  23031. this._updateBoundingInfo();
  23032. return this;
  23033. };
  23034. Mesh.prototype._createGlobalSubMesh = function (force) {
  23035. var totalVertices = this.getTotalVertices();
  23036. if (!totalVertices || !this.getIndices()) {
  23037. return null;
  23038. }
  23039. // Check if we need to recreate the submeshes
  23040. if (this.subMeshes && this.subMeshes.length > 0) {
  23041. var ib = this.getIndices();
  23042. if (!ib) {
  23043. return null;
  23044. }
  23045. var totalIndices = ib.length;
  23046. var needToRecreate = false;
  23047. if (force) {
  23048. needToRecreate = true;
  23049. }
  23050. else {
  23051. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  23052. var submesh = _a[_i];
  23053. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  23054. needToRecreate = true;
  23055. break;
  23056. }
  23057. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  23058. needToRecreate = true;
  23059. break;
  23060. }
  23061. }
  23062. }
  23063. if (!needToRecreate) {
  23064. return this.subMeshes[0];
  23065. }
  23066. }
  23067. this.releaseSubMeshes();
  23068. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  23069. };
  23070. Mesh.prototype.subdivide = function (count) {
  23071. if (count < 1) {
  23072. return;
  23073. }
  23074. var totalIndices = this.getTotalIndices();
  23075. var subdivisionSize = (totalIndices / count) | 0;
  23076. var offset = 0;
  23077. // Ensure that subdivisionSize is a multiple of 3
  23078. while (subdivisionSize % 3 !== 0) {
  23079. subdivisionSize++;
  23080. }
  23081. this.releaseSubMeshes();
  23082. for (var index = 0; index < count; index++) {
  23083. if (offset >= totalIndices) {
  23084. break;
  23085. }
  23086. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  23087. offset += subdivisionSize;
  23088. }
  23089. this.synchronizeInstances();
  23090. };
  23091. /**
  23092. * Sets the vertex data of the mesh geometry for the requested `kind`.
  23093. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  23094. * The `data` are either a numeric array either a Float32Array.
  23095. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  23096. * 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).
  23097. * Note that a new underlying VertexBuffer object is created each call.
  23098. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  23099. *
  23100. * Possible `kind` values :
  23101. * - BABYLON.VertexBuffer.PositionKind
  23102. * - BABYLON.VertexBuffer.UVKind
  23103. * - BABYLON.VertexBuffer.UV2Kind
  23104. * - BABYLON.VertexBuffer.UV3Kind
  23105. * - BABYLON.VertexBuffer.UV4Kind
  23106. * - BABYLON.VertexBuffer.UV5Kind
  23107. * - BABYLON.VertexBuffer.UV6Kind
  23108. * - BABYLON.VertexBuffer.ColorKind
  23109. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23110. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23111. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23112. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23113. *
  23114. * Returns the Mesh.
  23115. */
  23116. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23117. if (updatable === void 0) { updatable = false; }
  23118. if (!this._geometry) {
  23119. var vertexData = new BABYLON.VertexData();
  23120. vertexData.set(data, kind);
  23121. var scene = this.getScene();
  23122. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23123. }
  23124. else {
  23125. this._geometry.setVerticesData(kind, data, updatable, stride);
  23126. }
  23127. return this;
  23128. };
  23129. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  23130. if (updatable === void 0) { updatable = true; }
  23131. var vb = this.getVertexBuffer(kind);
  23132. if (!vb || vb.isUpdatable() === updatable) {
  23133. return;
  23134. }
  23135. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  23136. };
  23137. /**
  23138. * Sets the mesh VertexBuffer.
  23139. * Returns the Mesh.
  23140. */
  23141. Mesh.prototype.setVerticesBuffer = function (buffer) {
  23142. if (!this._geometry) {
  23143. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  23144. }
  23145. this._geometry.setVerticesBuffer(buffer);
  23146. return this;
  23147. };
  23148. /**
  23149. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  23150. * If the mesh has no geometry, it is simply returned as it is.
  23151. * The `data` are either a numeric array either a Float32Array.
  23152. * No new underlying VertexBuffer object is created.
  23153. * 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.
  23154. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  23155. *
  23156. * Possible `kind` values :
  23157. * - BABYLON.VertexBuffer.PositionKind
  23158. * - BABYLON.VertexBuffer.UVKind
  23159. * - BABYLON.VertexBuffer.UV2Kind
  23160. * - BABYLON.VertexBuffer.UV3Kind
  23161. * - BABYLON.VertexBuffer.UV4Kind
  23162. * - BABYLON.VertexBuffer.UV5Kind
  23163. * - BABYLON.VertexBuffer.UV6Kind
  23164. * - BABYLON.VertexBuffer.ColorKind
  23165. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23166. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23167. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23168. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23169. *
  23170. * Returns the Mesh.
  23171. */
  23172. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  23173. if (!this._geometry) {
  23174. return this;
  23175. }
  23176. if (!makeItUnique) {
  23177. this._geometry.updateVerticesData(kind, data, updateExtends);
  23178. }
  23179. else {
  23180. this.makeGeometryUnique();
  23181. this.updateVerticesData(kind, data, updateExtends, false);
  23182. }
  23183. return this;
  23184. };
  23185. /**
  23186. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  23187. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  23188. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  23189. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  23190. * Returns the Mesh.
  23191. */
  23192. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  23193. if (computeNormals === void 0) { computeNormals = true; }
  23194. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23195. if (!positions) {
  23196. return this;
  23197. }
  23198. positionFunction(positions);
  23199. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23200. if (computeNormals) {
  23201. var indices = this.getIndices();
  23202. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23203. if (!normals) {
  23204. return this;
  23205. }
  23206. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  23207. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23208. }
  23209. return this;
  23210. };
  23211. /**
  23212. * Creates a un-shared specific occurence of the geometry for the mesh.
  23213. * Returns the Mesh.
  23214. */
  23215. Mesh.prototype.makeGeometryUnique = function () {
  23216. if (!this._geometry) {
  23217. return this;
  23218. }
  23219. var oldGeometry = this._geometry;
  23220. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  23221. oldGeometry.releaseForMesh(this, true);
  23222. geometry.applyToMesh(this);
  23223. return this;
  23224. };
  23225. /**
  23226. * Sets the mesh indices.
  23227. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  23228. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  23229. * This method creates a new index buffer each call.
  23230. * Returns the Mesh.
  23231. */
  23232. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  23233. if (totalVertices === void 0) { totalVertices = null; }
  23234. if (updatable === void 0) { updatable = false; }
  23235. if (!this._geometry) {
  23236. var vertexData = new BABYLON.VertexData();
  23237. vertexData.indices = indices;
  23238. var scene = this.getScene();
  23239. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  23240. }
  23241. else {
  23242. this._geometry.setIndices(indices, totalVertices, updatable);
  23243. }
  23244. return this;
  23245. };
  23246. /**
  23247. * Update the current index buffer
  23248. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  23249. * Returns the Mesh.
  23250. */
  23251. Mesh.prototype.updateIndices = function (indices, offset) {
  23252. if (!this._geometry) {
  23253. return this;
  23254. }
  23255. this._geometry.updateIndices(indices, offset);
  23256. return this;
  23257. };
  23258. /**
  23259. * Invert the geometry to move from a right handed system to a left handed one.
  23260. * Returns the Mesh.
  23261. */
  23262. Mesh.prototype.toLeftHanded = function () {
  23263. if (!this._geometry) {
  23264. return this;
  23265. }
  23266. this._geometry.toLeftHanded();
  23267. return this;
  23268. };
  23269. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  23270. if (!this._geometry) {
  23271. return this;
  23272. }
  23273. var engine = this.getScene().getEngine();
  23274. // Wireframe
  23275. var indexToBind;
  23276. if (this._unIndexed) {
  23277. indexToBind = null;
  23278. }
  23279. else {
  23280. switch (fillMode) {
  23281. case BABYLON.Material.PointFillMode:
  23282. indexToBind = null;
  23283. break;
  23284. case BABYLON.Material.WireFrameFillMode:
  23285. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  23286. break;
  23287. default:
  23288. case BABYLON.Material.TriangleFillMode:
  23289. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  23290. break;
  23291. }
  23292. }
  23293. // VBOs
  23294. this._geometry._bind(effect, indexToBind);
  23295. return this;
  23296. };
  23297. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  23298. if (alternate === void 0) { alternate = false; }
  23299. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23300. return this;
  23301. }
  23302. this.onBeforeDrawObservable.notifyObservers(this);
  23303. var scene = this.getScene();
  23304. var engine = scene.getEngine();
  23305. // Draw order
  23306. switch (fillMode) {
  23307. case BABYLON.Material.PointFillMode:
  23308. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23309. break;
  23310. case BABYLON.Material.WireFrameFillMode:
  23311. if (this._unIndexed) {
  23312. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23313. }
  23314. else {
  23315. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  23316. }
  23317. break;
  23318. default:
  23319. if (this._unIndexed) {
  23320. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  23321. }
  23322. else {
  23323. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  23324. }
  23325. }
  23326. if (scene._isAlternateRenderingEnabled && !alternate) {
  23327. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  23328. if (!effect || !scene.activeCamera) {
  23329. return this;
  23330. }
  23331. scene._switchToAlternateCameraConfiguration(true);
  23332. this._effectiveMaterial.bindView(effect);
  23333. this._effectiveMaterial.bindViewProjection(effect);
  23334. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  23335. this._draw(subMesh, fillMode, instancesCount, true);
  23336. engine.setViewport(scene.activeCamera.viewport);
  23337. scene._switchToAlternateCameraConfiguration(false);
  23338. this._effectiveMaterial.bindView(effect);
  23339. this._effectiveMaterial.bindViewProjection(effect);
  23340. }
  23341. return this;
  23342. };
  23343. /**
  23344. * Registers for this mesh a javascript function called just before the rendering process.
  23345. * This function is passed the current mesh.
  23346. * Return the Mesh.
  23347. */
  23348. Mesh.prototype.registerBeforeRender = function (func) {
  23349. this.onBeforeRenderObservable.add(func);
  23350. return this;
  23351. };
  23352. /**
  23353. * Disposes a previously registered javascript function called before the rendering.
  23354. * This function is passed the current mesh.
  23355. * Returns the Mesh.
  23356. */
  23357. Mesh.prototype.unregisterBeforeRender = function (func) {
  23358. this.onBeforeRenderObservable.removeCallback(func);
  23359. return this;
  23360. };
  23361. /**
  23362. * Registers for this mesh a javascript function called just after the rendering is complete.
  23363. * This function is passed the current mesh.
  23364. * Returns the Mesh.
  23365. */
  23366. Mesh.prototype.registerAfterRender = function (func) {
  23367. this.onAfterRenderObservable.add(func);
  23368. return this;
  23369. };
  23370. /**
  23371. * Disposes a previously registered javascript function called after the rendering.
  23372. * This function is passed the current mesh.
  23373. * Return the Mesh.
  23374. */
  23375. Mesh.prototype.unregisterAfterRender = function (func) {
  23376. this.onAfterRenderObservable.removeCallback(func);
  23377. return this;
  23378. };
  23379. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  23380. var scene = this.getScene();
  23381. this._batchCache.mustReturn = false;
  23382. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  23383. this._batchCache.visibleInstances[subMeshId] = null;
  23384. if (this._visibleInstances) {
  23385. var currentRenderId = scene.getRenderId();
  23386. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  23387. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  23388. var selfRenderId = this._renderId;
  23389. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  23390. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  23391. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  23392. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  23393. }
  23394. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  23395. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  23396. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  23397. this._batchCache.mustReturn = true;
  23398. return this._batchCache;
  23399. }
  23400. if (currentRenderId !== selfRenderId) {
  23401. this._batchCache.renderSelf[subMeshId] = false;
  23402. }
  23403. }
  23404. this._renderIdForInstances[subMeshId] = currentRenderId;
  23405. }
  23406. return this._batchCache;
  23407. };
  23408. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  23409. var visibleInstances = batch.visibleInstances[subMesh._id];
  23410. if (!visibleInstances) {
  23411. return this;
  23412. }
  23413. var matricesCount = visibleInstances.length + 1;
  23414. var bufferSize = matricesCount * 16 * 4;
  23415. var currentInstancesBufferSize = this._instancesBufferSize;
  23416. var instancesBuffer = this._instancesBuffer;
  23417. while (this._instancesBufferSize < bufferSize) {
  23418. this._instancesBufferSize *= 2;
  23419. }
  23420. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  23421. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  23422. }
  23423. var offset = 0;
  23424. var instancesCount = 0;
  23425. var world = this.getWorldMatrix();
  23426. if (batch.renderSelf[subMesh._id]) {
  23427. world.copyToArray(this._instancesData, offset);
  23428. offset += 16;
  23429. instancesCount++;
  23430. }
  23431. if (visibleInstances) {
  23432. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  23433. var instance = visibleInstances[instanceIndex];
  23434. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  23435. offset += 16;
  23436. instancesCount++;
  23437. }
  23438. }
  23439. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  23440. if (instancesBuffer) {
  23441. instancesBuffer.dispose();
  23442. }
  23443. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  23444. this._instancesBuffer = instancesBuffer;
  23445. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  23446. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  23447. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  23448. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  23449. }
  23450. else {
  23451. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  23452. }
  23453. this._bind(subMesh, effect, fillMode);
  23454. this._draw(subMesh, fillMode, instancesCount);
  23455. engine.unbindInstanceAttributes();
  23456. return this;
  23457. };
  23458. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  23459. var scene = this.getScene();
  23460. var engine = scene.getEngine();
  23461. if (hardwareInstancedRendering) {
  23462. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  23463. }
  23464. else {
  23465. if (batch.renderSelf[subMesh._id]) {
  23466. // Draw
  23467. if (onBeforeDraw) {
  23468. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  23469. }
  23470. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  23471. }
  23472. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  23473. if (visibleInstancesForSubMesh) {
  23474. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  23475. var instance = visibleInstancesForSubMesh[instanceIndex];
  23476. // World
  23477. var world = instance.getWorldMatrix();
  23478. if (onBeforeDraw) {
  23479. onBeforeDraw(true, world, effectiveMaterial);
  23480. }
  23481. // Draw
  23482. this._draw(subMesh, fillMode);
  23483. }
  23484. }
  23485. }
  23486. return this;
  23487. };
  23488. /**
  23489. * Triggers the draw call for the mesh.
  23490. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  23491. * Returns the Mesh.
  23492. */
  23493. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  23494. this.checkOcclusionQuery();
  23495. if (this._isOccluded) {
  23496. return this;
  23497. }
  23498. var scene = this.getScene();
  23499. // Managing instances
  23500. var batch = this._getInstancesRenderList(subMesh._id);
  23501. if (batch.mustReturn) {
  23502. return this;
  23503. }
  23504. // Checking geometry state
  23505. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23506. return this;
  23507. }
  23508. this.onBeforeRenderObservable.notifyObservers(this);
  23509. var engine = scene.getEngine();
  23510. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23511. // Material
  23512. var material = subMesh.getMaterial();
  23513. if (!material) {
  23514. return this;
  23515. }
  23516. this._effectiveMaterial = material;
  23517. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23518. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  23519. return this;
  23520. }
  23521. }
  23522. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  23523. return this;
  23524. }
  23525. // Alpha mode
  23526. if (enableAlphaMode) {
  23527. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  23528. }
  23529. // Outline - step 1
  23530. var savedDepthWrite = engine.getDepthWrite();
  23531. if (this.renderOutline) {
  23532. engine.setDepthWrite(false);
  23533. scene.getOutlineRenderer().render(subMesh, batch);
  23534. engine.setDepthWrite(savedDepthWrite);
  23535. }
  23536. var effect;
  23537. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23538. effect = subMesh.effect;
  23539. }
  23540. else {
  23541. effect = this._effectiveMaterial.getEffect();
  23542. }
  23543. if (!effect) {
  23544. return this;
  23545. }
  23546. var reverse = this._effectiveMaterial._preBind(effect, this.overrideMaterialSideOrientation);
  23547. if (this._effectiveMaterial.forceDepthWrite) {
  23548. engine.setDepthWrite(true);
  23549. }
  23550. // Bind
  23551. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  23552. if (!hardwareInstancedRendering) {
  23553. this._bind(subMesh, effect, fillMode);
  23554. }
  23555. var world = this.getWorldMatrix();
  23556. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  23557. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  23558. }
  23559. else {
  23560. this._effectiveMaterial.bind(world, this);
  23561. }
  23562. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  23563. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  23564. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23565. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  23566. }
  23567. // Draw
  23568. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  23569. // Unbind
  23570. this._effectiveMaterial.unbind();
  23571. // Outline - step 2
  23572. if (this.renderOutline && savedDepthWrite) {
  23573. engine.setDepthWrite(true);
  23574. engine.setColorWrite(false);
  23575. scene.getOutlineRenderer().render(subMesh, batch);
  23576. engine.setColorWrite(true);
  23577. }
  23578. // Overlay
  23579. if (this.renderOverlay) {
  23580. var currentMode = engine.getAlphaMode();
  23581. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  23582. scene.getOutlineRenderer().render(subMesh, batch, true);
  23583. engine.setAlphaMode(currentMode);
  23584. }
  23585. this.onAfterRenderObservable.notifyObservers(this);
  23586. return this;
  23587. };
  23588. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  23589. if (isInstance) {
  23590. effectiveMaterial.bindOnlyWorldMatrix(world);
  23591. }
  23592. return this;
  23593. };
  23594. /**
  23595. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  23596. */
  23597. Mesh.prototype.getEmittedParticleSystems = function () {
  23598. var results = new Array();
  23599. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23600. var particleSystem = this.getScene().particleSystems[index];
  23601. if (particleSystem.emitter === this) {
  23602. results.push(particleSystem);
  23603. }
  23604. }
  23605. return results;
  23606. };
  23607. /**
  23608. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  23609. */
  23610. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  23611. var results = new Array();
  23612. var descendants = this.getDescendants();
  23613. descendants.push(this);
  23614. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  23615. var particleSystem = this.getScene().particleSystems[index];
  23616. var emitter = particleSystem.emitter;
  23617. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  23618. results.push(particleSystem);
  23619. }
  23620. }
  23621. return results;
  23622. };
  23623. Mesh.prototype._checkDelayState = function () {
  23624. var scene = this.getScene();
  23625. if (this._geometry) {
  23626. this._geometry.load(scene);
  23627. }
  23628. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23629. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23630. this._queueLoad(this, scene);
  23631. }
  23632. return this;
  23633. };
  23634. Mesh.prototype._queueLoad = function (mesh, scene) {
  23635. var _this = this;
  23636. scene._addPendingData(mesh);
  23637. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  23638. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23639. if (data instanceof ArrayBuffer) {
  23640. _this._delayLoadingFunction(data, _this);
  23641. }
  23642. else {
  23643. _this._delayLoadingFunction(JSON.parse(data), _this);
  23644. }
  23645. _this.instances.forEach(function (instance) {
  23646. instance._syncSubMeshes();
  23647. });
  23648. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23649. scene._removePendingData(_this);
  23650. }, function () { }, scene.database, getBinaryData);
  23651. return this;
  23652. };
  23653. /**
  23654. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  23655. */
  23656. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  23657. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23658. return false;
  23659. }
  23660. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  23661. return false;
  23662. }
  23663. this._checkDelayState();
  23664. return true;
  23665. };
  23666. /**
  23667. * Sets the mesh material by the material or multiMaterial `id` property.
  23668. * The material `id` is a string identifying the material or the multiMaterial.
  23669. * This method returns the Mesh.
  23670. */
  23671. Mesh.prototype.setMaterialByID = function (id) {
  23672. var materials = this.getScene().materials;
  23673. var index;
  23674. for (index = materials.length - 1; index > -1; index--) {
  23675. if (materials[index].id === id) {
  23676. this.material = materials[index];
  23677. return this;
  23678. }
  23679. }
  23680. // Multi
  23681. var multiMaterials = this.getScene().multiMaterials;
  23682. for (index = multiMaterials.length - 1; index > -1; index--) {
  23683. if (multiMaterials[index].id === id) {
  23684. this.material = multiMaterials[index];
  23685. return this;
  23686. }
  23687. }
  23688. return this;
  23689. };
  23690. /**
  23691. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  23692. */
  23693. Mesh.prototype.getAnimatables = function () {
  23694. var results = new Array();
  23695. if (this.material) {
  23696. results.push(this.material);
  23697. }
  23698. if (this.skeleton) {
  23699. results.push(this.skeleton);
  23700. }
  23701. return results;
  23702. };
  23703. /**
  23704. * Modifies the mesh geometry according to the passed transformation matrix.
  23705. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  23706. * The mesh normals are modified accordingly the same transformation.
  23707. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23708. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23709. * Returns the Mesh.
  23710. */
  23711. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  23712. // Position
  23713. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23714. return this;
  23715. }
  23716. var submeshes = this.subMeshes.splice(0);
  23717. this._resetPointsArrayCache();
  23718. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23719. var temp = new Array();
  23720. var index;
  23721. for (index = 0; index < data.length; index += 3) {
  23722. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  23723. }
  23724. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  23725. // Normals
  23726. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23727. return this;
  23728. }
  23729. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23730. temp = [];
  23731. for (index = 0; index < data.length; index += 3) {
  23732. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  23733. }
  23734. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  23735. // flip faces?
  23736. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  23737. this.flipFaces();
  23738. }
  23739. // Restore submeshes
  23740. this.releaseSubMeshes();
  23741. this.subMeshes = submeshes;
  23742. return this;
  23743. };
  23744. /**
  23745. * Modifies the mesh geometry according to its own current World Matrix.
  23746. * The mesh World Matrix is then reset.
  23747. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  23748. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  23749. * Note that, under the hood, this method sets a new VertexBuffer each call.
  23750. * Returns the Mesh.
  23751. */
  23752. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  23753. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  23754. this.scaling.copyFromFloats(1, 1, 1);
  23755. this.position.copyFromFloats(0, 0, 0);
  23756. this.rotation.copyFromFloats(0, 0, 0);
  23757. //only if quaternion is already set
  23758. if (this.rotationQuaternion) {
  23759. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  23760. }
  23761. this._worldMatrix = BABYLON.Matrix.Identity();
  23762. return this;
  23763. };
  23764. Object.defineProperty(Mesh.prototype, "_positions", {
  23765. // Cache
  23766. get: function () {
  23767. if (this._geometry) {
  23768. return this._geometry._positions;
  23769. }
  23770. return null;
  23771. },
  23772. enumerable: true,
  23773. configurable: true
  23774. });
  23775. Mesh.prototype._resetPointsArrayCache = function () {
  23776. if (this._geometry) {
  23777. this._geometry._resetPointsArrayCache();
  23778. }
  23779. return this;
  23780. };
  23781. Mesh.prototype._generatePointsArray = function () {
  23782. if (this._geometry) {
  23783. return this._geometry._generatePointsArray();
  23784. }
  23785. return false;
  23786. };
  23787. /**
  23788. * Returns a new Mesh object generated from the current mesh properties.
  23789. * This method must not get confused with createInstance().
  23790. * The parameter `name` is a string, the name given to the new mesh.
  23791. * The optional parameter `newParent` can be any Node object (default `null`).
  23792. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  23793. * 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.
  23794. */
  23795. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  23796. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23797. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  23798. };
  23799. /**
  23800. * Disposes the mesh.
  23801. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  23802. */
  23803. Mesh.prototype.dispose = function (doNotRecurse) {
  23804. var _this = this;
  23805. this.morphTargetManager = null;
  23806. if (this._geometry) {
  23807. this._geometry.releaseForMesh(this, true);
  23808. }
  23809. // Sources
  23810. var meshes = this.getScene().meshes;
  23811. meshes.forEach(function (mesh) {
  23812. if (mesh._source && mesh._source === _this) {
  23813. mesh._source = null;
  23814. }
  23815. });
  23816. this._source = null;
  23817. // Instances
  23818. if (this._instancesBuffer) {
  23819. this._instancesBuffer.dispose();
  23820. this._instancesBuffer = null;
  23821. }
  23822. while (this.instances.length) {
  23823. this.instances[0].dispose();
  23824. }
  23825. // Highlight layers.
  23826. var highlightLayers = this.getScene().highlightLayers;
  23827. for (var i = 0; i < highlightLayers.length; i++) {
  23828. var highlightLayer = highlightLayers[i];
  23829. if (highlightLayer) {
  23830. highlightLayer.removeMesh(this);
  23831. highlightLayer.removeExcludedMesh(this);
  23832. }
  23833. }
  23834. _super.prototype.dispose.call(this, doNotRecurse);
  23835. };
  23836. /**
  23837. * Modifies the mesh geometry according to a displacement map.
  23838. * 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.
  23839. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23840. * This method returns nothing.
  23841. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  23842. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23843. * 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.
  23844. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23845. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23846. *
  23847. * Returns the Mesh.
  23848. */
  23849. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  23850. var _this = this;
  23851. var scene = this.getScene();
  23852. var onload = function (img) {
  23853. // Getting height map data
  23854. var canvas = document.createElement("canvas");
  23855. var context = canvas.getContext("2d");
  23856. var heightMapWidth = img.width;
  23857. var heightMapHeight = img.height;
  23858. canvas.width = heightMapWidth;
  23859. canvas.height = heightMapHeight;
  23860. context.drawImage(img, 0, 0);
  23861. // Create VertexData from map data
  23862. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23863. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  23864. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  23865. //execute success callback, if set
  23866. if (onSuccess) {
  23867. onSuccess(_this);
  23868. }
  23869. };
  23870. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23871. return this;
  23872. };
  23873. /**
  23874. * Modifies the mesh geometry according to a displacementMap buffer.
  23875. * 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.
  23876. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  23877. * This method returns nothing.
  23878. * 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.
  23879. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  23880. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  23881. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  23882. * The parameter `uvScale` is an optional vector2 used to scale UV.
  23883. *
  23884. * Returns the Mesh.
  23885. */
  23886. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  23887. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  23888. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  23889. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23890. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  23891. return this;
  23892. }
  23893. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23894. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23895. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23896. var position = BABYLON.Vector3.Zero();
  23897. var normal = BABYLON.Vector3.Zero();
  23898. var uv = BABYLON.Vector2.Zero();
  23899. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  23900. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  23901. for (var index = 0; index < positions.length; index += 3) {
  23902. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  23903. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  23904. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  23905. // Compute height
  23906. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  23907. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  23908. var pos = (u + v * heightMapWidth) * 4;
  23909. var r = buffer[pos] / 255.0;
  23910. var g = buffer[pos + 1] / 255.0;
  23911. var b = buffer[pos + 2] / 255.0;
  23912. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  23913. normal.normalize();
  23914. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  23915. position = position.add(normal);
  23916. position.toArray(positions, index);
  23917. }
  23918. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  23919. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  23920. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  23921. return this;
  23922. };
  23923. /**
  23924. * Modify the mesh to get a flat shading rendering.
  23925. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  23926. * This method returns the Mesh.
  23927. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  23928. */
  23929. Mesh.prototype.convertToFlatShadedMesh = function () {
  23930. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  23931. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  23932. var kinds = this.getVerticesDataKinds();
  23933. var vbs = {};
  23934. var data = {};
  23935. var newdata = {};
  23936. var updatableNormals = false;
  23937. var kindIndex;
  23938. var kind;
  23939. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23940. kind = kinds[kindIndex];
  23941. var vertexBuffer = this.getVertexBuffer(kind);
  23942. if (kind === BABYLON.VertexBuffer.NormalKind) {
  23943. updatableNormals = vertexBuffer.isUpdatable();
  23944. kinds.splice(kindIndex, 1);
  23945. kindIndex--;
  23946. continue;
  23947. }
  23948. vbs[kind] = vertexBuffer;
  23949. data[kind] = vbs[kind].getData();
  23950. newdata[kind] = [];
  23951. }
  23952. // Save previous submeshes
  23953. var previousSubmeshes = this.subMeshes.slice(0);
  23954. var indices = this.getIndices();
  23955. var totalIndices = this.getTotalIndices();
  23956. // Generating unique vertices per face
  23957. var index;
  23958. for (index = 0; index < totalIndices; index++) {
  23959. var vertexIndex = indices[index];
  23960. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23961. kind = kinds[kindIndex];
  23962. var stride = vbs[kind].getStrideSize();
  23963. for (var offset = 0; offset < stride; offset++) {
  23964. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  23965. }
  23966. }
  23967. }
  23968. // Updating faces & normal
  23969. var normals = [];
  23970. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  23971. for (index = 0; index < totalIndices; index += 3) {
  23972. indices[index] = index;
  23973. indices[index + 1] = index + 1;
  23974. indices[index + 2] = index + 2;
  23975. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  23976. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  23977. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  23978. var p1p2 = p1.subtract(p2);
  23979. var p3p2 = p3.subtract(p2);
  23980. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23981. // Store same normals for every vertex
  23982. for (var localIndex = 0; localIndex < 3; localIndex++) {
  23983. normals.push(normal.x);
  23984. normals.push(normal.y);
  23985. normals.push(normal.z);
  23986. }
  23987. }
  23988. this.setIndices(indices);
  23989. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  23990. // Updating vertex buffers
  23991. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  23992. kind = kinds[kindIndex];
  23993. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  23994. }
  23995. // Updating submeshes
  23996. this.releaseSubMeshes();
  23997. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  23998. var previousOne = previousSubmeshes[submeshIndex];
  23999. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24000. }
  24001. this.synchronizeInstances();
  24002. return this;
  24003. };
  24004. /**
  24005. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  24006. * In other words, more vertices, no more indices and a single bigger VBO.
  24007. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  24008. * Returns the Mesh.
  24009. */
  24010. Mesh.prototype.convertToUnIndexedMesh = function () {
  24011. /// <summary>Remove indices by unfolding faces into buffers</summary>
  24012. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  24013. var kinds = this.getVerticesDataKinds();
  24014. var vbs = {};
  24015. var data = {};
  24016. var newdata = {};
  24017. var kindIndex;
  24018. var kind;
  24019. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24020. kind = kinds[kindIndex];
  24021. var vertexBuffer = this.getVertexBuffer(kind);
  24022. vbs[kind] = vertexBuffer;
  24023. data[kind] = vbs[kind].getData();
  24024. newdata[kind] = [];
  24025. }
  24026. // Save previous submeshes
  24027. var previousSubmeshes = this.subMeshes.slice(0);
  24028. var indices = this.getIndices();
  24029. var totalIndices = this.getTotalIndices();
  24030. // Generating unique vertices per face
  24031. var index;
  24032. for (index = 0; index < totalIndices; index++) {
  24033. var vertexIndex = indices[index];
  24034. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24035. kind = kinds[kindIndex];
  24036. var stride = vbs[kind].getStrideSize();
  24037. for (var offset = 0; offset < stride; offset++) {
  24038. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  24039. }
  24040. }
  24041. }
  24042. // Updating indices
  24043. for (index = 0; index < totalIndices; index += 3) {
  24044. indices[index] = index;
  24045. indices[index + 1] = index + 1;
  24046. indices[index + 2] = index + 2;
  24047. }
  24048. this.setIndices(indices);
  24049. // Updating vertex buffers
  24050. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  24051. kind = kinds[kindIndex];
  24052. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  24053. }
  24054. // Updating submeshes
  24055. this.releaseSubMeshes();
  24056. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  24057. var previousOne = previousSubmeshes[submeshIndex];
  24058. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  24059. }
  24060. this._unIndexed = true;
  24061. this.synchronizeInstances();
  24062. return this;
  24063. };
  24064. /**
  24065. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  24066. * This method returns the Mesh.
  24067. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  24068. */
  24069. Mesh.prototype.flipFaces = function (flipNormals) {
  24070. if (flipNormals === void 0) { flipNormals = false; }
  24071. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  24072. var i;
  24073. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  24074. for (i = 0; i < vertex_data.normals.length; i++) {
  24075. vertex_data.normals[i] *= -1;
  24076. }
  24077. }
  24078. if (vertex_data.indices) {
  24079. var temp;
  24080. for (i = 0; i < vertex_data.indices.length; i += 3) {
  24081. // reassign indices
  24082. temp = vertex_data.indices[i + 1];
  24083. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  24084. vertex_data.indices[i + 2] = temp;
  24085. }
  24086. }
  24087. vertex_data.applyToMesh(this);
  24088. return this;
  24089. };
  24090. // Instances
  24091. /**
  24092. * Creates a new InstancedMesh object from the mesh model.
  24093. * An instance shares the same properties and the same material than its model.
  24094. * Only these properties of each instance can then be set individually :
  24095. * - position
  24096. * - rotation
  24097. * - rotationQuaternion
  24098. * - setPivotMatrix
  24099. * - scaling
  24100. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  24101. * Warning : this method is not supported for Line mesh and LineSystem
  24102. */
  24103. Mesh.prototype.createInstance = function (name) {
  24104. return new BABYLON.InstancedMesh(name, this);
  24105. };
  24106. /**
  24107. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  24108. * After this call, all the mesh instances have the same submeshes than the current mesh.
  24109. * This method returns the Mesh.
  24110. */
  24111. Mesh.prototype.synchronizeInstances = function () {
  24112. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  24113. var instance = this.instances[instanceIndex];
  24114. instance._syncSubMeshes();
  24115. }
  24116. return this;
  24117. };
  24118. /**
  24119. * Simplify the mesh according to the given array of settings.
  24120. * Function will return immediately and will simplify async. It returns the Mesh.
  24121. * @param settings a collection of simplification settings.
  24122. * @param parallelProcessing should all levels calculate parallel or one after the other.
  24123. * @param type the type of simplification to run.
  24124. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  24125. */
  24126. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  24127. if (parallelProcessing === void 0) { parallelProcessing = true; }
  24128. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  24129. this.getScene().simplificationQueue.addTask({
  24130. settings: settings,
  24131. parallelProcessing: parallelProcessing,
  24132. mesh: this,
  24133. simplificationType: simplificationType,
  24134. successCallback: successCallback
  24135. });
  24136. return this;
  24137. };
  24138. /**
  24139. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  24140. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  24141. * This should be used together with the simplification to avoid disappearing triangles.
  24142. * Returns the Mesh.
  24143. * @param successCallback an optional success callback to be called after the optimization finished.
  24144. */
  24145. Mesh.prototype.optimizeIndices = function (successCallback) {
  24146. var _this = this;
  24147. var indices = this.getIndices();
  24148. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24149. if (!positions || !indices) {
  24150. return this;
  24151. }
  24152. var vectorPositions = new Array();
  24153. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  24154. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  24155. }
  24156. var dupes = new Array();
  24157. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  24158. var realPos = vectorPositions.length - 1 - iteration;
  24159. var testedPosition = vectorPositions[realPos];
  24160. for (var j = 0; j < realPos; ++j) {
  24161. var againstPosition = vectorPositions[j];
  24162. if (testedPosition.equals(againstPosition)) {
  24163. dupes[realPos] = j;
  24164. break;
  24165. }
  24166. }
  24167. }, function () {
  24168. for (var i = 0; i < indices.length; ++i) {
  24169. indices[i] = dupes[indices[i]] || indices[i];
  24170. }
  24171. //indices are now reordered
  24172. var originalSubMeshes = _this.subMeshes.slice(0);
  24173. _this.setIndices(indices);
  24174. _this.subMeshes = originalSubMeshes;
  24175. if (successCallback) {
  24176. successCallback(_this);
  24177. }
  24178. });
  24179. return this;
  24180. };
  24181. Mesh.prototype.serialize = function (serializationObject) {
  24182. serializationObject.name = this.name;
  24183. serializationObject.id = this.id;
  24184. serializationObject.type = this.getClassName();
  24185. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  24186. serializationObject.tags = BABYLON.Tags.GetTags(this);
  24187. }
  24188. serializationObject.position = this.position.asArray();
  24189. if (this.rotationQuaternion) {
  24190. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  24191. }
  24192. else if (this.rotation) {
  24193. serializationObject.rotation = this.rotation.asArray();
  24194. }
  24195. serializationObject.scaling = this.scaling.asArray();
  24196. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  24197. serializationObject.isEnabled = this.isEnabled();
  24198. serializationObject.isVisible = this.isVisible;
  24199. serializationObject.infiniteDistance = this.infiniteDistance;
  24200. serializationObject.pickable = this.isPickable;
  24201. serializationObject.receiveShadows = this.receiveShadows;
  24202. serializationObject.billboardMode = this.billboardMode;
  24203. serializationObject.visibility = this.visibility;
  24204. serializationObject.checkCollisions = this.checkCollisions;
  24205. serializationObject.isBlocker = this.isBlocker;
  24206. // Parent
  24207. if (this.parent) {
  24208. serializationObject.parentId = this.parent.id;
  24209. }
  24210. // Geometry
  24211. var geometry = this._geometry;
  24212. if (geometry) {
  24213. var geometryId = geometry.id;
  24214. serializationObject.geometryId = geometryId;
  24215. // SubMeshes
  24216. serializationObject.subMeshes = [];
  24217. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  24218. var subMesh = this.subMeshes[subIndex];
  24219. serializationObject.subMeshes.push({
  24220. materialIndex: subMesh.materialIndex,
  24221. verticesStart: subMesh.verticesStart,
  24222. verticesCount: subMesh.verticesCount,
  24223. indexStart: subMesh.indexStart,
  24224. indexCount: subMesh.indexCount
  24225. });
  24226. }
  24227. }
  24228. // Material
  24229. if (this.material) {
  24230. serializationObject.materialId = this.material.id;
  24231. }
  24232. else {
  24233. this.material = null;
  24234. }
  24235. // Morph targets
  24236. if (this.morphTargetManager) {
  24237. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  24238. }
  24239. // Skeleton
  24240. if (this.skeleton) {
  24241. serializationObject.skeletonId = this.skeleton.id;
  24242. }
  24243. // Physics
  24244. //TODO implement correct serialization for physics impostors.
  24245. var impostor = this.getPhysicsImpostor();
  24246. if (impostor) {
  24247. serializationObject.physicsMass = impostor.getParam("mass");
  24248. serializationObject.physicsFriction = impostor.getParam("friction");
  24249. serializationObject.physicsRestitution = impostor.getParam("mass");
  24250. serializationObject.physicsImpostor = impostor.type;
  24251. }
  24252. // Metadata
  24253. if (this.metadata) {
  24254. serializationObject.metadata = this.metadata;
  24255. }
  24256. // Instances
  24257. serializationObject.instances = [];
  24258. for (var index = 0; index < this.instances.length; index++) {
  24259. var instance = this.instances[index];
  24260. var serializationInstance = {
  24261. name: instance.name,
  24262. position: instance.position.asArray(),
  24263. scaling: instance.scaling.asArray()
  24264. };
  24265. if (instance.rotationQuaternion) {
  24266. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  24267. }
  24268. else if (instance.rotation) {
  24269. serializationInstance.rotation = instance.rotation.asArray();
  24270. }
  24271. serializationObject.instances.push(serializationInstance);
  24272. // Animations
  24273. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  24274. serializationInstance.ranges = instance.serializeAnimationRanges();
  24275. }
  24276. //
  24277. // Animations
  24278. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24279. serializationObject.ranges = this.serializeAnimationRanges();
  24280. // Layer mask
  24281. serializationObject.layerMask = this.layerMask;
  24282. // Alpha
  24283. serializationObject.alphaIndex = this.alphaIndex;
  24284. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  24285. // Overlay
  24286. serializationObject.overlayAlpha = this.overlayAlpha;
  24287. serializationObject.overlayColor = this.overlayColor.asArray();
  24288. serializationObject.renderOverlay = this.renderOverlay;
  24289. // Fog
  24290. serializationObject.applyFog = this.applyFog;
  24291. // Action Manager
  24292. if (this.actionManager) {
  24293. serializationObject.actions = this.actionManager.serialize(this.name);
  24294. }
  24295. };
  24296. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  24297. if (!this.geometry) {
  24298. return;
  24299. }
  24300. this._markSubMeshesAsAttributesDirty();
  24301. var morphTargetManager = this._morphTargetManager;
  24302. if (morphTargetManager && morphTargetManager.vertexCount) {
  24303. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  24304. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  24305. this.morphTargetManager = null;
  24306. return;
  24307. }
  24308. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  24309. var morphTarget = morphTargetManager.getActiveTarget(index);
  24310. var positions = morphTarget.getPositions();
  24311. if (!positions) {
  24312. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  24313. return;
  24314. }
  24315. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  24316. var normals = morphTarget.getNormals();
  24317. if (normals) {
  24318. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  24319. }
  24320. var tangents = morphTarget.getTangents();
  24321. if (tangents) {
  24322. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  24323. }
  24324. }
  24325. }
  24326. else {
  24327. var index = 0;
  24328. // Positions
  24329. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  24330. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  24331. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  24332. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  24333. }
  24334. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  24335. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  24336. }
  24337. index++;
  24338. }
  24339. }
  24340. };
  24341. // Statics
  24342. /**
  24343. * Returns a new Mesh object what is a deep copy of the passed mesh.
  24344. * The parameter `parsedMesh` is the mesh to be copied.
  24345. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  24346. */
  24347. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  24348. var mesh;
  24349. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  24350. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  24351. }
  24352. else {
  24353. mesh = new Mesh(parsedMesh.name, scene);
  24354. }
  24355. mesh.id = parsedMesh.id;
  24356. if (BABYLON.Tags) {
  24357. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  24358. }
  24359. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  24360. if (parsedMesh.metadata !== undefined) {
  24361. mesh.metadata = parsedMesh.metadata;
  24362. }
  24363. if (parsedMesh.rotationQuaternion) {
  24364. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  24365. }
  24366. else if (parsedMesh.rotation) {
  24367. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  24368. }
  24369. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  24370. if (parsedMesh.localMatrix) {
  24371. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  24372. }
  24373. else if (parsedMesh.pivotMatrix) {
  24374. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  24375. }
  24376. mesh.setEnabled(parsedMesh.isEnabled);
  24377. mesh.isVisible = parsedMesh.isVisible;
  24378. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  24379. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  24380. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  24381. if (parsedMesh.applyFog !== undefined) {
  24382. mesh.applyFog = parsedMesh.applyFog;
  24383. }
  24384. if (parsedMesh.pickable !== undefined) {
  24385. mesh.isPickable = parsedMesh.pickable;
  24386. }
  24387. if (parsedMesh.alphaIndex !== undefined) {
  24388. mesh.alphaIndex = parsedMesh.alphaIndex;
  24389. }
  24390. mesh.receiveShadows = parsedMesh.receiveShadows;
  24391. mesh.billboardMode = parsedMesh.billboardMode;
  24392. if (parsedMesh.visibility !== undefined) {
  24393. mesh.visibility = parsedMesh.visibility;
  24394. }
  24395. mesh.checkCollisions = parsedMesh.checkCollisions;
  24396. if (parsedMesh.isBlocker !== undefined) {
  24397. mesh.isBlocker = parsedMesh.isBlocker;
  24398. }
  24399. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  24400. // freezeWorldMatrix
  24401. if (parsedMesh.freezeWorldMatrix) {
  24402. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  24403. }
  24404. // Parent
  24405. if (parsedMesh.parentId) {
  24406. mesh._waitingParentId = parsedMesh.parentId;
  24407. }
  24408. // Actions
  24409. if (parsedMesh.actions !== undefined) {
  24410. mesh._waitingActions = parsedMesh.actions;
  24411. }
  24412. // Overlay
  24413. if (parsedMesh.overlayAlpha !== undefined) {
  24414. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  24415. }
  24416. if (parsedMesh.overlayColor !== undefined) {
  24417. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  24418. }
  24419. if (parsedMesh.renderOverlay !== undefined) {
  24420. mesh.renderOverlay = parsedMesh.renderOverlay;
  24421. }
  24422. // Geometry
  24423. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  24424. if (parsedMesh.delayLoadingFile) {
  24425. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24426. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  24427. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  24428. if (parsedMesh._binaryInfo) {
  24429. mesh._binaryInfo = parsedMesh._binaryInfo;
  24430. }
  24431. mesh._delayInfo = [];
  24432. if (parsedMesh.hasUVs) {
  24433. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  24434. }
  24435. if (parsedMesh.hasUVs2) {
  24436. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  24437. }
  24438. if (parsedMesh.hasUVs3) {
  24439. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  24440. }
  24441. if (parsedMesh.hasUVs4) {
  24442. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  24443. }
  24444. if (parsedMesh.hasUVs5) {
  24445. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  24446. }
  24447. if (parsedMesh.hasUVs6) {
  24448. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  24449. }
  24450. if (parsedMesh.hasColors) {
  24451. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  24452. }
  24453. if (parsedMesh.hasMatricesIndices) {
  24454. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24455. }
  24456. if (parsedMesh.hasMatricesWeights) {
  24457. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24458. }
  24459. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  24460. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  24461. mesh._checkDelayState();
  24462. }
  24463. }
  24464. else {
  24465. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  24466. }
  24467. // Material
  24468. if (parsedMesh.materialId) {
  24469. mesh.setMaterialByID(parsedMesh.materialId);
  24470. }
  24471. else {
  24472. mesh.material = null;
  24473. }
  24474. // Morph targets
  24475. if (parsedMesh.morphTargetManagerId > -1) {
  24476. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  24477. }
  24478. // Skeleton
  24479. if (parsedMesh.skeletonId > -1) {
  24480. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  24481. if (parsedMesh.numBoneInfluencers) {
  24482. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  24483. }
  24484. }
  24485. // Animations
  24486. if (parsedMesh.animations) {
  24487. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24488. var parsedAnimation = parsedMesh.animations[animationIndex];
  24489. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24490. }
  24491. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  24492. }
  24493. if (parsedMesh.autoAnimate) {
  24494. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  24495. }
  24496. // Layer Mask
  24497. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  24498. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  24499. }
  24500. else {
  24501. mesh.layerMask = 0x0FFFFFFF;
  24502. }
  24503. // Physics
  24504. if (parsedMesh.physicsImpostor) {
  24505. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  24506. mass: parsedMesh.physicsMass,
  24507. friction: parsedMesh.physicsFriction,
  24508. restitution: parsedMesh.physicsRestitution
  24509. }, scene);
  24510. }
  24511. // Instances
  24512. if (parsedMesh.instances) {
  24513. for (var index = 0; index < parsedMesh.instances.length; index++) {
  24514. var parsedInstance = parsedMesh.instances[index];
  24515. var instance = mesh.createInstance(parsedInstance.name);
  24516. if (BABYLON.Tags) {
  24517. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  24518. }
  24519. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  24520. if (parsedInstance.parentId) {
  24521. instance._waitingParentId = parsedInstance.parentId;
  24522. }
  24523. if (parsedInstance.rotationQuaternion) {
  24524. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  24525. }
  24526. else if (parsedInstance.rotation) {
  24527. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  24528. }
  24529. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  24530. instance.checkCollisions = mesh.checkCollisions;
  24531. if (parsedMesh.animations) {
  24532. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  24533. parsedAnimation = parsedMesh.animations[animationIndex];
  24534. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24535. }
  24536. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  24537. }
  24538. }
  24539. }
  24540. return mesh;
  24541. };
  24542. /**
  24543. * Creates a ribbon mesh.
  24544. * Please consider using the same method from the MeshBuilder class instead.
  24545. * 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.
  24546. *
  24547. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  24548. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  24549. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  24550. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  24551. * 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.
  24552. * 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.
  24553. * 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
  24554. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24555. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24557. */
  24558. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  24559. if (closeArray === void 0) { closeArray = false; }
  24560. if (updatable === void 0) { updatable = false; }
  24561. return BABYLON.MeshBuilder.CreateRibbon(name, {
  24562. pathArray: pathArray,
  24563. closeArray: closeArray,
  24564. closePath: closePath,
  24565. offset: offset,
  24566. updatable: updatable,
  24567. sideOrientation: sideOrientation,
  24568. instance: instance
  24569. }, scene);
  24570. };
  24571. /**
  24572. * Creates a plane polygonal mesh. By default, this is a disc.
  24573. * Please consider using the same method from the MeshBuilder class instead.
  24574. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  24575. * 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.
  24576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24579. */
  24580. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  24581. if (scene === void 0) { scene = null; }
  24582. var options = {
  24583. radius: radius,
  24584. tessellation: tessellation,
  24585. sideOrientation: sideOrientation,
  24586. updatable: updatable
  24587. };
  24588. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  24589. };
  24590. /**
  24591. * Creates a box mesh.
  24592. * Please consider using the same method from the MeshBuilder class instead.
  24593. * The parameter `size` sets the size (float) of each box side (default 1).
  24594. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24595. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24596. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24597. */
  24598. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  24599. if (scene === void 0) { scene = null; }
  24600. var options = {
  24601. size: size,
  24602. sideOrientation: sideOrientation,
  24603. updatable: updatable
  24604. };
  24605. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  24606. };
  24607. /**
  24608. * Creates a sphere mesh.
  24609. * Please consider using the same method from the MeshBuilder class instead.
  24610. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  24611. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  24612. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24613. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24615. */
  24616. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  24617. var options = {
  24618. segments: segments,
  24619. diameterX: diameter,
  24620. diameterY: diameter,
  24621. diameterZ: diameter,
  24622. sideOrientation: sideOrientation,
  24623. updatable: updatable
  24624. };
  24625. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  24626. };
  24627. /**
  24628. * Creates a cylinder or a cone mesh.
  24629. * Please consider using the same method from the MeshBuilder class instead.
  24630. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  24631. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  24632. * 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.
  24633. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  24634. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  24635. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24636. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24637. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24638. */
  24639. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  24640. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  24641. if (scene !== undefined) {
  24642. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  24643. updatable = scene;
  24644. }
  24645. scene = subdivisions;
  24646. subdivisions = 1;
  24647. }
  24648. var options = {
  24649. height: height,
  24650. diameterTop: diameterTop,
  24651. diameterBottom: diameterBottom,
  24652. tessellation: tessellation,
  24653. subdivisions: subdivisions,
  24654. sideOrientation: sideOrientation,
  24655. updatable: updatable
  24656. };
  24657. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  24658. };
  24659. // Torus (Code from SharpDX.org)
  24660. /**
  24661. * Creates a torus mesh.
  24662. * Please consider using the same method from the MeshBuilder class instead.
  24663. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  24664. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  24665. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  24666. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24667. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24668. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24669. */
  24670. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  24671. var options = {
  24672. diameter: diameter,
  24673. thickness: thickness,
  24674. tessellation: tessellation,
  24675. sideOrientation: sideOrientation,
  24676. updatable: updatable
  24677. };
  24678. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  24679. };
  24680. /**
  24681. * Creates a torus knot mesh.
  24682. * Please consider using the same method from the MeshBuilder class instead.
  24683. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  24684. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  24685. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  24686. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  24687. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24688. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24689. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24690. */
  24691. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  24692. var options = {
  24693. radius: radius,
  24694. tube: tube,
  24695. radialSegments: radialSegments,
  24696. tubularSegments: tubularSegments,
  24697. p: p,
  24698. q: q,
  24699. sideOrientation: sideOrientation,
  24700. updatable: updatable
  24701. };
  24702. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  24703. };
  24704. /**
  24705. * Creates a line mesh.
  24706. * Please consider using the same method from the MeshBuilder class instead.
  24707. * 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.
  24708. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24709. * The parameter `points` is an array successive Vector3.
  24710. * 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
  24711. * When updating an instance, remember that only point positions can change, not the number of points.
  24712. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24713. */
  24714. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  24715. if (scene === void 0) { scene = null; }
  24716. if (updatable === void 0) { updatable = false; }
  24717. if (instance === void 0) { instance = null; }
  24718. var options = {
  24719. points: points,
  24720. updatable: updatable,
  24721. instance: instance
  24722. };
  24723. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  24724. };
  24725. /**
  24726. * Creates a dashed line mesh.
  24727. * Please consider using the same method from the MeshBuilder class instead.
  24728. * 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.
  24729. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  24730. * The parameter `points` is an array successive Vector3.
  24731. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  24732. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  24733. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  24734. * 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
  24735. * When updating an instance, remember that only point positions can change, not the number of points.
  24736. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24737. */
  24738. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  24739. if (scene === void 0) { scene = null; }
  24740. var options = {
  24741. points: points,
  24742. dashSize: dashSize,
  24743. gapSize: gapSize,
  24744. dashNb: dashNb,
  24745. updatable: updatable,
  24746. instance: instance
  24747. };
  24748. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  24749. };
  24750. /**
  24751. * Creates a polygon mesh.
  24752. * Please consider using the same method from the MeshBuilder class instead.
  24753. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  24754. * 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.
  24755. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24756. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24757. * Remember you can only change the shape positions, not their number when updating a polygon.
  24758. */
  24759. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  24760. var options = {
  24761. shape: shape,
  24762. holes: holes,
  24763. updatable: updatable,
  24764. sideOrientation: sideOrientation
  24765. };
  24766. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  24767. };
  24768. /**
  24769. * Creates an extruded polygon mesh, with depth in the Y direction.
  24770. * Please consider using the same method from the MeshBuilder class instead.
  24771. */
  24772. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  24773. var options = {
  24774. shape: shape,
  24775. holes: holes,
  24776. depth: depth,
  24777. updatable: updatable,
  24778. sideOrientation: sideOrientation
  24779. };
  24780. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  24781. };
  24782. /**
  24783. * Creates an extruded shape mesh.
  24784. * 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.
  24785. * Please consider using the same method from the MeshBuilder class instead.
  24786. *
  24787. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24788. * 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
  24789. * extruded along the Z axis.
  24790. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24791. * 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.
  24792. * The parameter `scale` (float, default 1) is the value to scale the shape.
  24793. * 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
  24794. * 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
  24795. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24796. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24797. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24799. */
  24800. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  24801. if (scene === void 0) { scene = null; }
  24802. var options = {
  24803. shape: shape,
  24804. path: path,
  24805. scale: scale,
  24806. rotation: rotation,
  24807. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24808. sideOrientation: sideOrientation,
  24809. instance: instance,
  24810. updatable: updatable
  24811. };
  24812. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  24813. };
  24814. /**
  24815. * Creates an custom extruded shape mesh.
  24816. * 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.
  24817. * Please consider using the same method from the MeshBuilder class instead.
  24818. *
  24819. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  24820. * 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
  24821. * extruded along the Z axis.
  24822. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  24823. * 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
  24824. * and the distance of this point from the begining of the path :
  24825. * ```javascript
  24826. * var rotationFunction = function(i, distance) {
  24827. * // do things
  24828. * return rotationValue; }
  24829. * ```
  24830. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  24831. * 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
  24832. * and the distance of this point from the begining of the path :
  24833. * ```javascript
  24834. * var scaleFunction = function(i, distance) {
  24835. * // do things
  24836. * return scaleValue;}
  24837. * ```
  24838. * It must returns a float value that will be the scale value applied to the shape on each path point.
  24839. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  24840. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  24841. * 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
  24842. * 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
  24843. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  24844. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24845. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24846. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24847. */
  24848. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  24849. var options = {
  24850. shape: shape,
  24851. path: path,
  24852. scaleFunction: scaleFunction,
  24853. rotationFunction: rotationFunction,
  24854. ribbonCloseArray: ribbonCloseArray,
  24855. ribbonClosePath: ribbonClosePath,
  24856. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  24857. sideOrientation: sideOrientation,
  24858. instance: instance,
  24859. updatable: updatable
  24860. };
  24861. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  24862. };
  24863. /**
  24864. * Creates lathe mesh.
  24865. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  24866. * Please consider using the same method from the MeshBuilder class instead.
  24867. * 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
  24868. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  24869. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  24870. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  24871. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24872. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24873. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24874. */
  24875. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  24876. var options = {
  24877. shape: shape,
  24878. radius: radius,
  24879. tessellation: tessellation,
  24880. sideOrientation: sideOrientation,
  24881. updatable: updatable
  24882. };
  24883. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  24884. };
  24885. /**
  24886. * Creates a plane mesh.
  24887. * Please consider using the same method from the MeshBuilder class instead.
  24888. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  24889. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24890. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24891. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24892. */
  24893. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  24894. var options = {
  24895. size: size,
  24896. width: size,
  24897. height: size,
  24898. sideOrientation: sideOrientation,
  24899. updatable: updatable
  24900. };
  24901. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  24902. };
  24903. /**
  24904. * Creates a ground mesh.
  24905. * Please consider using the same method from the MeshBuilder class instead.
  24906. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  24907. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  24908. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24909. */
  24910. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  24911. var options = {
  24912. width: width,
  24913. height: height,
  24914. subdivisions: subdivisions,
  24915. updatable: updatable
  24916. };
  24917. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  24918. };
  24919. /**
  24920. * Creates a tiled ground mesh.
  24921. * Please consider using the same method from the MeshBuilder class instead.
  24922. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  24923. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  24924. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  24925. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  24926. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  24927. * numbers of subdivisions on the ground width and height of each tile.
  24928. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24929. */
  24930. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  24931. var options = {
  24932. xmin: xmin,
  24933. zmin: zmin,
  24934. xmax: xmax,
  24935. zmax: zmax,
  24936. subdivisions: subdivisions,
  24937. precision: precision,
  24938. updatable: updatable
  24939. };
  24940. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  24941. };
  24942. /**
  24943. * Creates a ground mesh from a height map.
  24944. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  24945. * Please consider using the same method from the MeshBuilder class instead.
  24946. * The parameter `url` sets the URL of the height map image resource.
  24947. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  24948. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  24949. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  24950. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  24951. * 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).
  24952. * This function is passed the newly built mesh :
  24953. * ```javascript
  24954. * function(mesh) { // do things
  24955. * return; }
  24956. * ```
  24957. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24958. */
  24959. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  24960. var options = {
  24961. width: width,
  24962. height: height,
  24963. subdivisions: subdivisions,
  24964. minHeight: minHeight,
  24965. maxHeight: maxHeight,
  24966. updatable: updatable,
  24967. onReady: onReady
  24968. };
  24969. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  24970. };
  24971. /**
  24972. * Creates a tube mesh.
  24973. * 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.
  24974. * Please consider using the same method from the MeshBuilder class instead.
  24975. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  24976. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  24977. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  24978. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  24979. * 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.
  24980. * It must return a radius value (positive float) :
  24981. * ```javascript
  24982. * var radiusFunction = function(i, distance) {
  24983. * // do things
  24984. * return radius; }
  24985. * ```
  24986. * 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
  24987. * 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
  24988. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  24989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  24990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  24991. */
  24992. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  24993. var options = {
  24994. path: path,
  24995. radius: radius,
  24996. tessellation: tessellation,
  24997. radiusFunction: radiusFunction,
  24998. arc: 1,
  24999. cap: cap,
  25000. updatable: updatable,
  25001. sideOrientation: sideOrientation,
  25002. instance: instance
  25003. };
  25004. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  25005. };
  25006. /**
  25007. * Creates a polyhedron mesh.
  25008. * Please consider using the same method from the MeshBuilder class instead.
  25009. * 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
  25010. * to choose the wanted type.
  25011. * The parameter `size` (positive float, default 1) sets the polygon size.
  25012. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  25013. * 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`.
  25014. * 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
  25015. * 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)`).
  25016. * 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
  25017. * 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.
  25018. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25019. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25020. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25021. */
  25022. Mesh.CreatePolyhedron = function (name, options, scene) {
  25023. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  25024. };
  25025. /**
  25026. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  25027. * Please consider using the same method from the MeshBuilder class instead.
  25028. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  25029. * 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`).
  25030. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  25031. * 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.
  25032. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25033. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25035. */
  25036. Mesh.CreateIcoSphere = function (name, options, scene) {
  25037. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  25038. };
  25039. /**
  25040. * Creates a decal mesh.
  25041. * Please consider using the same method from the MeshBuilder class instead.
  25042. * 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.
  25043. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  25044. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  25045. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  25046. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  25047. */
  25048. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  25049. var options = {
  25050. position: position,
  25051. normal: normal,
  25052. size: size,
  25053. angle: angle
  25054. };
  25055. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  25056. };
  25057. // Skeletons
  25058. /**
  25059. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25060. */
  25061. Mesh.prototype.setPositionsForCPUSkinning = function () {
  25062. if (!this._sourcePositions) {
  25063. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25064. if (!source) {
  25065. return this._sourcePositions;
  25066. }
  25067. this._sourcePositions = new Float32Array(source);
  25068. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  25069. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  25070. }
  25071. }
  25072. return this._sourcePositions;
  25073. };
  25074. /**
  25075. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  25076. */
  25077. Mesh.prototype.setNormalsForCPUSkinning = function () {
  25078. if (!this._sourceNormals) {
  25079. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25080. if (!source) {
  25081. return this._sourceNormals;
  25082. }
  25083. this._sourceNormals = new Float32Array(source);
  25084. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  25085. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  25086. }
  25087. }
  25088. return this._sourceNormals;
  25089. };
  25090. /**
  25091. * Updates the vertex buffer by applying transformation from the bones.
  25092. * Returns the Mesh.
  25093. *
  25094. * @param {skeleton} skeleton to apply
  25095. */
  25096. Mesh.prototype.applySkeleton = function (skeleton) {
  25097. if (!this.geometry) {
  25098. return this;
  25099. }
  25100. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  25101. return this;
  25102. }
  25103. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  25104. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  25105. return this;
  25106. }
  25107. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25108. return this;
  25109. }
  25110. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  25111. return this;
  25112. }
  25113. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  25114. return this;
  25115. }
  25116. if (!this._sourcePositions) {
  25117. var submeshes = this.subMeshes.slice();
  25118. this.setPositionsForCPUSkinning();
  25119. this.subMeshes = submeshes;
  25120. }
  25121. if (!this._sourceNormals) {
  25122. this.setNormalsForCPUSkinning();
  25123. }
  25124. // positionsData checks for not being Float32Array will only pass at most once
  25125. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25126. if (!positionsData) {
  25127. return this;
  25128. }
  25129. if (!(positionsData instanceof Float32Array)) {
  25130. positionsData = new Float32Array(positionsData);
  25131. }
  25132. // normalsData checks for not being Float32Array will only pass at most once
  25133. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25134. if (!normalsData) {
  25135. return this;
  25136. }
  25137. if (!(normalsData instanceof Float32Array)) {
  25138. normalsData = new Float32Array(normalsData);
  25139. }
  25140. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25141. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25142. if (!matricesWeightsData || !matricesIndicesData) {
  25143. return this;
  25144. }
  25145. var needExtras = this.numBoneInfluencers > 4;
  25146. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25147. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25148. if (!matricesWeightsExtraData || !matricesIndicesExtraData) {
  25149. return this;
  25150. }
  25151. var skeletonMatrices = skeleton.getTransformMatrices(this);
  25152. var tempVector3 = BABYLON.Vector3.Zero();
  25153. var finalMatrix = new BABYLON.Matrix();
  25154. var tempMatrix = new BABYLON.Matrix();
  25155. var matWeightIdx = 0;
  25156. var inf;
  25157. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  25158. var weight;
  25159. for (inf = 0; inf < 4; inf++) {
  25160. weight = matricesWeightsData[matWeightIdx + inf];
  25161. if (weight > 0) {
  25162. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25163. finalMatrix.addToSelf(tempMatrix);
  25164. }
  25165. else
  25166. break;
  25167. }
  25168. if (needExtras) {
  25169. for (inf = 0; inf < 4; inf++) {
  25170. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25171. if (weight > 0) {
  25172. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25173. finalMatrix.addToSelf(tempMatrix);
  25174. }
  25175. else
  25176. break;
  25177. }
  25178. }
  25179. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  25180. tempVector3.toArray(positionsData, index);
  25181. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  25182. tempVector3.toArray(normalsData, index);
  25183. finalMatrix.reset();
  25184. }
  25185. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  25186. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  25187. return this;
  25188. };
  25189. // Tools
  25190. /**
  25191. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  25192. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  25193. */
  25194. Mesh.MinMax = function (meshes) {
  25195. var minVector = null;
  25196. var maxVector = null;
  25197. meshes.forEach(function (mesh, index, array) {
  25198. var boundingInfo = mesh.getBoundingInfo();
  25199. if (!boundingInfo) {
  25200. return;
  25201. }
  25202. var boundingBox = boundingInfo.boundingBox;
  25203. if (!minVector || !maxVector) {
  25204. minVector = boundingBox.minimumWorld;
  25205. maxVector = boundingBox.maximumWorld;
  25206. }
  25207. else {
  25208. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  25209. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  25210. }
  25211. });
  25212. if (!minVector || !maxVector) {
  25213. return {
  25214. min: BABYLON.Vector3.Zero(),
  25215. max: BABYLON.Vector3.Zero()
  25216. };
  25217. }
  25218. return {
  25219. min: minVector,
  25220. max: maxVector
  25221. };
  25222. };
  25223. /**
  25224. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  25225. */
  25226. Mesh.Center = function (meshesOrMinMaxVector) {
  25227. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  25228. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  25229. };
  25230. /**
  25231. * Merge the array of meshes into a single mesh for performance reasons.
  25232. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  25233. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  25234. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  25235. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  25236. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  25237. */
  25238. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  25239. if (disposeSource === void 0) { disposeSource = true; }
  25240. var index;
  25241. if (!allow32BitsIndices) {
  25242. var totalVertices = 0;
  25243. // Counting vertices
  25244. for (index = 0; index < meshes.length; index++) {
  25245. if (meshes[index]) {
  25246. totalVertices += meshes[index].getTotalVertices();
  25247. if (totalVertices > 65536) {
  25248. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  25249. return null;
  25250. }
  25251. }
  25252. }
  25253. }
  25254. // Merge
  25255. var vertexData = null;
  25256. var otherVertexData;
  25257. var indiceArray = new Array();
  25258. var source = null;
  25259. for (index = 0; index < meshes.length; index++) {
  25260. if (meshes[index]) {
  25261. meshes[index].computeWorldMatrix(true);
  25262. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  25263. otherVertexData.transform(meshes[index].getWorldMatrix());
  25264. if (vertexData) {
  25265. vertexData.merge(otherVertexData);
  25266. }
  25267. else {
  25268. vertexData = otherVertexData;
  25269. source = meshes[index];
  25270. }
  25271. if (subdivideWithSubMeshes) {
  25272. indiceArray.push(meshes[index].getTotalIndices());
  25273. }
  25274. }
  25275. }
  25276. source = source;
  25277. if (!meshSubclass) {
  25278. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  25279. }
  25280. vertexData.applyToMesh(meshSubclass);
  25281. // Setting properties
  25282. meshSubclass.material = source.material;
  25283. meshSubclass.checkCollisions = source.checkCollisions;
  25284. // Cleaning
  25285. if (disposeSource) {
  25286. for (index = 0; index < meshes.length; index++) {
  25287. if (meshes[index]) {
  25288. meshes[index].dispose();
  25289. }
  25290. }
  25291. }
  25292. // Subdivide
  25293. if (subdivideWithSubMeshes) {
  25294. //-- Suppresions du submesh global
  25295. meshSubclass.releaseSubMeshes();
  25296. index = 0;
  25297. var offset = 0;
  25298. //-- aplique la subdivision en fonction du tableau d'indices
  25299. while (index < indiceArray.length) {
  25300. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  25301. offset += indiceArray[index];
  25302. index++;
  25303. }
  25304. }
  25305. return meshSubclass;
  25306. };
  25307. // Consts
  25308. Mesh._FRONTSIDE = 0;
  25309. Mesh._BACKSIDE = 1;
  25310. Mesh._DOUBLESIDE = 2;
  25311. Mesh._DEFAULTSIDE = 0;
  25312. Mesh._NO_CAP = 0;
  25313. Mesh._CAP_START = 1;
  25314. Mesh._CAP_END = 2;
  25315. Mesh._CAP_ALL = 3;
  25316. return Mesh;
  25317. }(BABYLON.AbstractMesh));
  25318. BABYLON.Mesh = Mesh;
  25319. })(BABYLON || (BABYLON = {}));
  25320. //# sourceMappingURL=babylon.mesh.js.map
  25321. var BABYLON;
  25322. (function (BABYLON) {
  25323. var BaseSubMesh = /** @class */ (function () {
  25324. function BaseSubMesh() {
  25325. }
  25326. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  25327. get: function () {
  25328. return this._materialEffect;
  25329. },
  25330. enumerable: true,
  25331. configurable: true
  25332. });
  25333. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  25334. if (defines === void 0) { defines = null; }
  25335. if (this._materialEffect === effect) {
  25336. if (!effect) {
  25337. this._materialDefines = null;
  25338. }
  25339. return;
  25340. }
  25341. this._materialDefines = defines;
  25342. this._materialEffect = effect;
  25343. };
  25344. return BaseSubMesh;
  25345. }());
  25346. BABYLON.BaseSubMesh = BaseSubMesh;
  25347. var SubMesh = /** @class */ (function (_super) {
  25348. __extends(SubMesh, _super);
  25349. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25350. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25351. var _this = _super.call(this) || this;
  25352. _this.materialIndex = materialIndex;
  25353. _this.verticesStart = verticesStart;
  25354. _this.verticesCount = verticesCount;
  25355. _this.indexStart = indexStart;
  25356. _this.indexCount = indexCount;
  25357. _this._renderId = 0;
  25358. _this._mesh = mesh;
  25359. _this._renderingMesh = renderingMesh || mesh;
  25360. mesh.subMeshes.push(_this);
  25361. _this._trianglePlanes = [];
  25362. _this._id = mesh.subMeshes.length - 1;
  25363. if (createBoundingBox) {
  25364. _this.refreshBoundingInfo();
  25365. mesh.computeWorldMatrix(true);
  25366. }
  25367. return _this;
  25368. }
  25369. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  25370. if (createBoundingBox === void 0) { createBoundingBox = true; }
  25371. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  25372. };
  25373. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  25374. get: function () {
  25375. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  25376. },
  25377. enumerable: true,
  25378. configurable: true
  25379. });
  25380. /**
  25381. * Returns the submesh BoudingInfo object.
  25382. */
  25383. SubMesh.prototype.getBoundingInfo = function () {
  25384. if (this.IsGlobal) {
  25385. return this._mesh.getBoundingInfo();
  25386. }
  25387. return this._boundingInfo;
  25388. };
  25389. /**
  25390. * Sets the submesh BoundingInfo.
  25391. * Return the SubMesh.
  25392. */
  25393. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  25394. this._boundingInfo = boundingInfo;
  25395. return this;
  25396. };
  25397. /**
  25398. * Returns the mesh of the current submesh.
  25399. */
  25400. SubMesh.prototype.getMesh = function () {
  25401. return this._mesh;
  25402. };
  25403. /**
  25404. * Returns the rendering mesh of the submesh.
  25405. */
  25406. SubMesh.prototype.getRenderingMesh = function () {
  25407. return this._renderingMesh;
  25408. };
  25409. /**
  25410. * Returns the submesh material.
  25411. */
  25412. SubMesh.prototype.getMaterial = function () {
  25413. var rootMaterial = this._renderingMesh.material;
  25414. if (rootMaterial && rootMaterial.getSubMaterial) {
  25415. var multiMaterial = rootMaterial;
  25416. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  25417. if (this._currentMaterial !== effectiveMaterial) {
  25418. this._currentMaterial = effectiveMaterial;
  25419. this._materialDefines = null;
  25420. }
  25421. return effectiveMaterial;
  25422. }
  25423. if (!rootMaterial) {
  25424. return this._mesh.getScene().defaultMaterial;
  25425. }
  25426. return rootMaterial;
  25427. };
  25428. // Methods
  25429. /**
  25430. * Sets a new updated BoundingInfo object to the submesh.
  25431. * Returns the SubMesh.
  25432. */
  25433. SubMesh.prototype.refreshBoundingInfo = function () {
  25434. this._lastColliderWorldVertices = null;
  25435. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  25436. return this;
  25437. }
  25438. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25439. if (!data) {
  25440. this._boundingInfo = this._mesh._boundingInfo;
  25441. return this;
  25442. }
  25443. var indices = this._renderingMesh.getIndices();
  25444. var extend;
  25445. //is this the only submesh?
  25446. if (this.indexStart === 0 && this.indexCount === indices.length) {
  25447. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25448. if (!boundingInfo) {
  25449. return this;
  25450. }
  25451. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  25452. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  25453. }
  25454. else {
  25455. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  25456. }
  25457. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25458. return this;
  25459. };
  25460. SubMesh.prototype._checkCollision = function (collider) {
  25461. var boundingInfo = this._renderingMesh.getBoundingInfo();
  25462. if (!boundingInfo) {
  25463. return false;
  25464. }
  25465. return boundingInfo._checkCollision(collider);
  25466. };
  25467. /**
  25468. * Updates the submesh BoundingInfo.
  25469. * Returns the Submesh.
  25470. */
  25471. SubMesh.prototype.updateBoundingInfo = function (world) {
  25472. var boundingInfo = this.getBoundingInfo();
  25473. if (!boundingInfo) {
  25474. this.refreshBoundingInfo();
  25475. boundingInfo = this.getBoundingInfo();
  25476. }
  25477. boundingInfo.update(world);
  25478. return this;
  25479. };
  25480. /**
  25481. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  25482. * Boolean returned.
  25483. */
  25484. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  25485. var boundingInfo = this.getBoundingInfo();
  25486. if (!boundingInfo) {
  25487. return false;
  25488. }
  25489. return boundingInfo.isInFrustum(frustumPlanes);
  25490. };
  25491. /**
  25492. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  25493. * Boolean returned.
  25494. */
  25495. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  25496. var boundingInfo = this.getBoundingInfo();
  25497. if (!boundingInfo) {
  25498. return false;
  25499. }
  25500. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  25501. };
  25502. /**
  25503. * Renders the submesh.
  25504. * Returns it.
  25505. */
  25506. SubMesh.prototype.render = function (enableAlphaMode) {
  25507. this._renderingMesh.render(this, enableAlphaMode);
  25508. return this;
  25509. };
  25510. /**
  25511. * Returns a new Index Buffer.
  25512. * Type returned : WebGLBuffer.
  25513. */
  25514. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  25515. if (!this._linesIndexBuffer) {
  25516. var linesIndices = [];
  25517. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25518. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  25519. }
  25520. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  25521. this.linesIndexCount = linesIndices.length;
  25522. }
  25523. return this._linesIndexBuffer;
  25524. };
  25525. /**
  25526. * True is the passed Ray intersects the submesh bounding box.
  25527. * Boolean returned.
  25528. */
  25529. SubMesh.prototype.canIntersects = function (ray) {
  25530. var boundingInfo = this.getBoundingInfo();
  25531. if (!boundingInfo) {
  25532. return false;
  25533. }
  25534. return ray.intersectsBox(boundingInfo.boundingBox);
  25535. };
  25536. /**
  25537. * Returns an object IntersectionInfo.
  25538. */
  25539. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  25540. var intersectInfo = null;
  25541. // LineMesh first as it's also a Mesh...
  25542. if (this._mesh instanceof BABYLON.LinesMesh) {
  25543. var lineMesh = this._mesh;
  25544. // Line test
  25545. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  25546. var p0 = positions[indices[index]];
  25547. var p1 = positions[indices[index + 1]];
  25548. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  25549. if (length < 0) {
  25550. continue;
  25551. }
  25552. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  25553. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  25554. if (fastCheck) {
  25555. break;
  25556. }
  25557. }
  25558. }
  25559. }
  25560. else {
  25561. // Triangles test
  25562. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  25563. var p0 = positions[indices[index]];
  25564. var p1 = positions[indices[index + 1]];
  25565. var p2 = positions[indices[index + 2]];
  25566. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  25567. if (currentIntersectInfo) {
  25568. if (currentIntersectInfo.distance < 0) {
  25569. continue;
  25570. }
  25571. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  25572. intersectInfo = currentIntersectInfo;
  25573. intersectInfo.faceId = index / 3;
  25574. if (fastCheck) {
  25575. break;
  25576. }
  25577. }
  25578. }
  25579. }
  25580. }
  25581. return intersectInfo;
  25582. };
  25583. SubMesh.prototype._rebuild = function () {
  25584. if (this._linesIndexBuffer) {
  25585. this._linesIndexBuffer = null;
  25586. }
  25587. };
  25588. // Clone
  25589. /**
  25590. * Creates a new Submesh from the passed Mesh.
  25591. */
  25592. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  25593. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  25594. if (!this.IsGlobal) {
  25595. var boundingInfo = this.getBoundingInfo();
  25596. if (!boundingInfo) {
  25597. return result;
  25598. }
  25599. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  25600. }
  25601. return result;
  25602. };
  25603. // Dispose
  25604. /**
  25605. * Disposes the Submesh.
  25606. * Returns nothing.
  25607. */
  25608. SubMesh.prototype.dispose = function () {
  25609. if (this._linesIndexBuffer) {
  25610. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  25611. this._linesIndexBuffer = null;
  25612. }
  25613. // Remove from mesh
  25614. var index = this._mesh.subMeshes.indexOf(this);
  25615. this._mesh.subMeshes.splice(index, 1);
  25616. };
  25617. // Statics
  25618. /**
  25619. * Creates a new Submesh from the passed parameters :
  25620. * - materialIndex (integer) : the index of the main mesh material.
  25621. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  25622. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  25623. * - mesh (Mesh) : the main mesh to create the submesh from.
  25624. * - renderingMesh (optional Mesh) : rendering mesh.
  25625. */
  25626. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  25627. var minVertexIndex = Number.MAX_VALUE;
  25628. var maxVertexIndex = -Number.MAX_VALUE;
  25629. renderingMesh = (renderingMesh || mesh);
  25630. var indices = renderingMesh.getIndices();
  25631. for (var index = startIndex; index < startIndex + indexCount; index++) {
  25632. var vertexIndex = indices[index];
  25633. if (vertexIndex < minVertexIndex)
  25634. minVertexIndex = vertexIndex;
  25635. if (vertexIndex > maxVertexIndex)
  25636. maxVertexIndex = vertexIndex;
  25637. }
  25638. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  25639. };
  25640. return SubMesh;
  25641. }(BaseSubMesh));
  25642. BABYLON.SubMesh = SubMesh;
  25643. })(BABYLON || (BABYLON = {}));
  25644. //# sourceMappingURL=babylon.subMesh.js.map
  25645. var BABYLON;
  25646. (function (BABYLON) {
  25647. var EffectFallbacks = /** @class */ (function () {
  25648. function EffectFallbacks() {
  25649. this._defines = {};
  25650. this._currentRank = 32;
  25651. this._maxRank = -1;
  25652. }
  25653. EffectFallbacks.prototype.unBindMesh = function () {
  25654. this._mesh = null;
  25655. };
  25656. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25657. if (!this._defines[rank]) {
  25658. if (rank < this._currentRank) {
  25659. this._currentRank = rank;
  25660. }
  25661. if (rank > this._maxRank) {
  25662. this._maxRank = rank;
  25663. }
  25664. this._defines[rank] = new Array();
  25665. }
  25666. this._defines[rank].push(define);
  25667. };
  25668. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25669. this._meshRank = rank;
  25670. this._mesh = mesh;
  25671. if (rank < this._currentRank) {
  25672. this._currentRank = rank;
  25673. }
  25674. if (rank > this._maxRank) {
  25675. this._maxRank = rank;
  25676. }
  25677. };
  25678. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25679. get: function () {
  25680. return this._currentRank <= this._maxRank;
  25681. },
  25682. enumerable: true,
  25683. configurable: true
  25684. });
  25685. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25686. // First we try to switch to CPU skinning
  25687. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  25688. this._mesh.computeBonesUsingShaders = false;
  25689. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25690. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25691. var scene = this._mesh.getScene();
  25692. for (var index = 0; index < scene.meshes.length; index++) {
  25693. var otherMesh = scene.meshes[index];
  25694. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  25695. otherMesh.computeBonesUsingShaders = false;
  25696. }
  25697. }
  25698. }
  25699. else {
  25700. var currentFallbacks = this._defines[this._currentRank];
  25701. if (currentFallbacks) {
  25702. for (var index = 0; index < currentFallbacks.length; index++) {
  25703. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25704. }
  25705. }
  25706. this._currentRank++;
  25707. }
  25708. return currentDefines;
  25709. };
  25710. return EffectFallbacks;
  25711. }());
  25712. BABYLON.EffectFallbacks = EffectFallbacks;
  25713. var EffectCreationOptions = /** @class */ (function () {
  25714. function EffectCreationOptions() {
  25715. }
  25716. return EffectCreationOptions;
  25717. }());
  25718. BABYLON.EffectCreationOptions = EffectCreationOptions;
  25719. var Effect = /** @class */ (function () {
  25720. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25721. if (samplers === void 0) { samplers = null; }
  25722. if (defines === void 0) { defines = null; }
  25723. if (fallbacks === void 0) { fallbacks = null; }
  25724. if (onCompiled === void 0) { onCompiled = null; }
  25725. if (onError === void 0) { onError = null; }
  25726. var _this = this;
  25727. this.uniqueId = 0;
  25728. this.onCompileObservable = new BABYLON.Observable();
  25729. this.onErrorObservable = new BABYLON.Observable();
  25730. this.onBindObservable = new BABYLON.Observable();
  25731. this._uniformBuffersNames = {};
  25732. this._isReady = false;
  25733. this._compilationError = "";
  25734. this.name = baseName;
  25735. if (attributesNamesOrOptions.attributes) {
  25736. var options = attributesNamesOrOptions;
  25737. this._engine = uniformsNamesOrEngine;
  25738. this._attributesNames = options.attributes;
  25739. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  25740. this._samplers = options.samplers;
  25741. this.defines = options.defines;
  25742. this.onError = options.onError;
  25743. this.onCompiled = options.onCompiled;
  25744. this._fallbacks = options.fallbacks;
  25745. this._indexParameters = options.indexParameters;
  25746. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  25747. if (options.uniformBuffersNames) {
  25748. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  25749. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  25750. }
  25751. }
  25752. }
  25753. else {
  25754. this._engine = engine;
  25755. this.defines = defines;
  25756. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  25757. this._samplers = samplers;
  25758. this._attributesNames = attributesNamesOrOptions;
  25759. this.onError = onError;
  25760. this.onCompiled = onCompiled;
  25761. this._indexParameters = indexParameters;
  25762. this._fallbacks = fallbacks;
  25763. }
  25764. this.uniqueId = Effect._uniqueIdSeed++;
  25765. var vertexSource;
  25766. var fragmentSource;
  25767. if (baseName.vertexElement) {
  25768. vertexSource = document.getElementById(baseName.vertexElement);
  25769. if (!vertexSource) {
  25770. vertexSource = baseName.vertexElement;
  25771. }
  25772. }
  25773. else {
  25774. vertexSource = baseName.vertex || baseName;
  25775. }
  25776. if (baseName.fragmentElement) {
  25777. fragmentSource = document.getElementById(baseName.fragmentElement);
  25778. if (!fragmentSource) {
  25779. fragmentSource = baseName.fragmentElement;
  25780. }
  25781. }
  25782. else {
  25783. fragmentSource = baseName.fragment || baseName;
  25784. }
  25785. this._loadVertexShader(vertexSource, function (vertexCode) {
  25786. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25787. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25788. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25789. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25790. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25791. if (baseName) {
  25792. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  25793. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  25794. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  25795. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  25796. }
  25797. else {
  25798. _this._vertexSourceCode = migratedVertexCode;
  25799. _this._fragmentSourceCode = migratedFragmentCode;
  25800. }
  25801. _this._prepareEffect();
  25802. });
  25803. });
  25804. });
  25805. });
  25806. });
  25807. });
  25808. }
  25809. Object.defineProperty(Effect.prototype, "key", {
  25810. get: function () {
  25811. return this._key;
  25812. },
  25813. enumerable: true,
  25814. configurable: true
  25815. });
  25816. // Properties
  25817. Effect.prototype.isReady = function () {
  25818. return this._isReady;
  25819. };
  25820. Effect.prototype.getEngine = function () {
  25821. return this._engine;
  25822. };
  25823. Effect.prototype.getProgram = function () {
  25824. return this._program;
  25825. };
  25826. Effect.prototype.getAttributesNames = function () {
  25827. return this._attributesNames;
  25828. };
  25829. Effect.prototype.getAttributeLocation = function (index) {
  25830. return this._attributes[index];
  25831. };
  25832. Effect.prototype.getAttributeLocationByName = function (name) {
  25833. var index = this._attributesNames.indexOf(name);
  25834. return this._attributes[index];
  25835. };
  25836. Effect.prototype.getAttributesCount = function () {
  25837. return this._attributes.length;
  25838. };
  25839. Effect.prototype.getUniformIndex = function (uniformName) {
  25840. return this._uniformsNames.indexOf(uniformName);
  25841. };
  25842. Effect.prototype.getUniform = function (uniformName) {
  25843. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25844. };
  25845. Effect.prototype.getSamplers = function () {
  25846. return this._samplers;
  25847. };
  25848. Effect.prototype.getCompilationError = function () {
  25849. return this._compilationError;
  25850. };
  25851. // Methods
  25852. Effect.prototype.executeWhenCompiled = function (func) {
  25853. if (this.isReady()) {
  25854. func(this);
  25855. return;
  25856. }
  25857. this.onCompileObservable.add(function (effect) {
  25858. func(effect);
  25859. });
  25860. };
  25861. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25862. if (BABYLON.Tools.IsWindowObjectExist()) {
  25863. // DOM element ?
  25864. if (vertex instanceof HTMLElement) {
  25865. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25866. callback(vertexCode);
  25867. return;
  25868. }
  25869. }
  25870. // Base64 encoded ?
  25871. if (vertex.substr(0, 7) === "base64:") {
  25872. var vertexBinary = window.atob(vertex.substr(7));
  25873. callback(vertexBinary);
  25874. return;
  25875. }
  25876. // Is in local store ?
  25877. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25878. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25879. return;
  25880. }
  25881. var vertexShaderUrl;
  25882. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25883. vertexShaderUrl = vertex;
  25884. }
  25885. else {
  25886. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25887. }
  25888. // Vertex shader
  25889. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25890. };
  25891. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25892. if (BABYLON.Tools.IsWindowObjectExist()) {
  25893. // DOM element ?
  25894. if (fragment instanceof HTMLElement) {
  25895. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25896. callback(fragmentCode);
  25897. return;
  25898. }
  25899. }
  25900. // Base64 encoded ?
  25901. if (fragment.substr(0, 7) === "base64:") {
  25902. var fragmentBinary = window.atob(fragment.substr(7));
  25903. callback(fragmentBinary);
  25904. return;
  25905. }
  25906. // Is in local store ?
  25907. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25908. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25909. return;
  25910. }
  25911. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25912. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25913. return;
  25914. }
  25915. var fragmentShaderUrl;
  25916. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25917. fragmentShaderUrl = fragment;
  25918. }
  25919. else {
  25920. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25921. }
  25922. // Fragment shader
  25923. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25924. };
  25925. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  25926. // Rebuild shaders source code
  25927. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  25928. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  25929. vertexCode = prefix + vertexCode;
  25930. fragmentCode = prefix + fragmentCode;
  25931. // Number lines of shaders source code
  25932. var i = 2;
  25933. var regex = /\n/gm;
  25934. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25935. i = 2;
  25936. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  25937. // Dump shaders name and formatted source code
  25938. if (this.name.vertexElement) {
  25939. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  25940. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  25941. }
  25942. else if (this.name.vertex) {
  25943. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  25944. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  25945. }
  25946. else {
  25947. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  25948. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  25949. }
  25950. };
  25951. ;
  25952. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  25953. var preparedSourceCode = this._processPrecision(sourceCode);
  25954. if (this._engine.webGLVersion == 1) {
  25955. callback(preparedSourceCode);
  25956. return;
  25957. }
  25958. // Already converted
  25959. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  25960. callback(preparedSourceCode.replace("#version 300 es", ""));
  25961. return;
  25962. }
  25963. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  25964. // Remove extensions
  25965. // #extension GL_OES_standard_derivatives : enable
  25966. // #extension GL_EXT_shader_texture_lod : enable
  25967. // #extension GL_EXT_frag_depth : enable
  25968. // #extension GL_EXT_draw_buffers : require
  25969. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  25970. var result = preparedSourceCode.replace(regex, "");
  25971. // Migrate to GLSL v300
  25972. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  25973. result = result.replace(/attribute[ \t]/g, "in ");
  25974. result = result.replace(/[ \t]attribute/g, " in");
  25975. if (isFragment) {
  25976. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  25977. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  25978. result = result.replace(/texture2D\s*\(/g, "texture(");
  25979. result = result.replace(/textureCube\s*\(/g, "texture(");
  25980. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  25981. result = result.replace(/gl_FragColor/g, "glFragColor");
  25982. result = result.replace(/gl_FragData/g, "glFragData");
  25983. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  25984. }
  25985. callback(result);
  25986. };
  25987. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25988. var _this = this;
  25989. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25990. var match = regex.exec(sourceCode);
  25991. var returnValue = new String(sourceCode);
  25992. while (match != null) {
  25993. var includeFile = match[1];
  25994. // Uniform declaration
  25995. if (includeFile.indexOf("__decl__") !== -1) {
  25996. includeFile = includeFile.replace(/__decl__/, "");
  25997. if (this._engine.supportsUniformBuffers) {
  25998. includeFile = includeFile.replace(/Vertex/, "Ubo");
  25999. includeFile = includeFile.replace(/Fragment/, "Ubo");
  26000. }
  26001. includeFile = includeFile + "Declaration";
  26002. }
  26003. if (Effect.IncludesShadersStore[includeFile]) {
  26004. // Substitution
  26005. var includeContent = Effect.IncludesShadersStore[includeFile];
  26006. if (match[2]) {
  26007. var splits = match[3].split(",");
  26008. for (var index = 0; index < splits.length; index += 2) {
  26009. var source = new RegExp(splits[index], "g");
  26010. var dest = splits[index + 1];
  26011. includeContent = includeContent.replace(source, dest);
  26012. }
  26013. }
  26014. if (match[4]) {
  26015. var indexString = match[5];
  26016. if (indexString.indexOf("..") !== -1) {
  26017. var indexSplits = indexString.split("..");
  26018. var minIndex = parseInt(indexSplits[0]);
  26019. var maxIndex = parseInt(indexSplits[1]);
  26020. var sourceIncludeContent = includeContent.slice(0);
  26021. includeContent = "";
  26022. if (isNaN(maxIndex)) {
  26023. maxIndex = this._indexParameters[indexSplits[1]];
  26024. }
  26025. for (var i = minIndex; i < maxIndex; i++) {
  26026. if (!this._engine.supportsUniformBuffers) {
  26027. // Ubo replacement
  26028. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26029. return p1 + "{X}";
  26030. });
  26031. }
  26032. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  26033. }
  26034. }
  26035. else {
  26036. if (!this._engine.supportsUniformBuffers) {
  26037. // Ubo replacement
  26038. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  26039. return p1 + "{X}";
  26040. });
  26041. }
  26042. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26043. }
  26044. }
  26045. // Replace
  26046. returnValue = returnValue.replace(match[0], includeContent);
  26047. }
  26048. else {
  26049. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26050. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26051. Effect.IncludesShadersStore[includeFile] = fileContent;
  26052. _this._processIncludes(returnValue, callback);
  26053. });
  26054. return;
  26055. }
  26056. match = regex.exec(sourceCode);
  26057. }
  26058. callback(returnValue);
  26059. };
  26060. Effect.prototype._processPrecision = function (source) {
  26061. if (source.indexOf("precision highp float") === -1) {
  26062. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26063. source = "precision mediump float;\n" + source;
  26064. }
  26065. else {
  26066. source = "precision highp float;\n" + source;
  26067. }
  26068. }
  26069. else {
  26070. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26071. source = source.replace("precision highp float", "precision mediump float");
  26072. }
  26073. }
  26074. return source;
  26075. };
  26076. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  26077. var _this = this;
  26078. this._isReady = false;
  26079. this._vertexSourceCodeOverride = vertexSourceCode;
  26080. this._fragmentSourceCodeOverride = fragmentSourceCode;
  26081. this.onError = function (effect, error) {
  26082. if (onError) {
  26083. onError(error);
  26084. }
  26085. };
  26086. this.onCompiled = function () {
  26087. var scenes = _this.getEngine().scenes;
  26088. for (var i = 0; i < scenes.length; i++) {
  26089. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26090. }
  26091. if (onCompiled) {
  26092. onCompiled(_this._program);
  26093. }
  26094. };
  26095. this._fallbacks = null;
  26096. this._prepareEffect();
  26097. };
  26098. Effect.prototype._prepareEffect = function () {
  26099. var attributesNames = this._attributesNames;
  26100. var defines = this.defines;
  26101. var fallbacks = this._fallbacks;
  26102. this._valueCache = {};
  26103. var previousProgram = this._program;
  26104. try {
  26105. var engine = this._engine;
  26106. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  26107. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  26108. }
  26109. else {
  26110. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  26111. }
  26112. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  26113. if (engine.webGLVersion > 1) {
  26114. for (var name in this._uniformBuffersNames) {
  26115. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  26116. }
  26117. }
  26118. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26119. this._attributes = engine.getAttributes(this._program, attributesNames);
  26120. var index;
  26121. for (index = 0; index < this._samplers.length; index++) {
  26122. var sampler = this.getUniform(this._samplers[index]);
  26123. if (sampler == null) {
  26124. this._samplers.splice(index, 1);
  26125. index--;
  26126. }
  26127. }
  26128. engine.bindSamplers(this);
  26129. this._compilationError = "";
  26130. this._isReady = true;
  26131. if (this.onCompiled) {
  26132. this.onCompiled(this);
  26133. }
  26134. this.onCompileObservable.notifyObservers(this);
  26135. this.onCompileObservable.clear();
  26136. // Unbind mesh reference in fallbacks
  26137. if (this._fallbacks) {
  26138. this._fallbacks.unBindMesh();
  26139. }
  26140. if (previousProgram) {
  26141. this.getEngine()._deleteProgram(previousProgram);
  26142. }
  26143. }
  26144. catch (e) {
  26145. this._compilationError = e.message;
  26146. // Let's go through fallbacks then
  26147. BABYLON.Tools.Error("Unable to compile effect:");
  26148. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  26149. return " " + uniform;
  26150. }));
  26151. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  26152. return " " + attribute;
  26153. }));
  26154. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  26155. BABYLON.Tools.Error("Error: " + this._compilationError);
  26156. if (previousProgram) {
  26157. this._program = previousProgram;
  26158. this._isReady = true;
  26159. if (this.onError) {
  26160. this.onError(this, this._compilationError);
  26161. }
  26162. this.onErrorObservable.notifyObservers(this);
  26163. }
  26164. if (fallbacks && fallbacks.isMoreFallbacks) {
  26165. BABYLON.Tools.Error("Trying next fallback.");
  26166. this.defines = fallbacks.reduce(this.defines);
  26167. this._prepareEffect();
  26168. }
  26169. else {
  26170. if (this.onError) {
  26171. this.onError(this, this._compilationError);
  26172. }
  26173. this.onErrorObservable.notifyObservers(this);
  26174. this.onErrorObservable.clear();
  26175. // Unbind mesh reference in fallbacks
  26176. if (this._fallbacks) {
  26177. this._fallbacks.unBindMesh();
  26178. }
  26179. }
  26180. }
  26181. };
  26182. Object.defineProperty(Effect.prototype, "isSupported", {
  26183. get: function () {
  26184. return this._compilationError === "";
  26185. },
  26186. enumerable: true,
  26187. configurable: true
  26188. });
  26189. Effect.prototype._bindTexture = function (channel, texture) {
  26190. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26191. };
  26192. Effect.prototype.setTexture = function (channel, texture) {
  26193. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26194. };
  26195. Effect.prototype.setTextureArray = function (channel, textures) {
  26196. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26197. var initialPos = this._samplers.indexOf(channel);
  26198. for (var index = 1; index < textures.length; index++) {
  26199. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26200. }
  26201. }
  26202. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26203. };
  26204. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26205. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26206. };
  26207. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26208. var cache = this._valueCache[uniformName];
  26209. var flag = matrix.updateFlag;
  26210. if (cache !== undefined && cache === flag) {
  26211. return false;
  26212. }
  26213. this._valueCache[uniformName] = flag;
  26214. return true;
  26215. };
  26216. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26217. var cache = this._valueCache[uniformName];
  26218. if (!cache) {
  26219. cache = [x, y];
  26220. this._valueCache[uniformName] = cache;
  26221. return true;
  26222. }
  26223. var changed = false;
  26224. if (cache[0] !== x) {
  26225. cache[0] = x;
  26226. changed = true;
  26227. }
  26228. if (cache[1] !== y) {
  26229. cache[1] = y;
  26230. changed = true;
  26231. }
  26232. return changed;
  26233. };
  26234. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26235. var cache = this._valueCache[uniformName];
  26236. if (!cache) {
  26237. cache = [x, y, z];
  26238. this._valueCache[uniformName] = cache;
  26239. return true;
  26240. }
  26241. var changed = false;
  26242. if (cache[0] !== x) {
  26243. cache[0] = x;
  26244. changed = true;
  26245. }
  26246. if (cache[1] !== y) {
  26247. cache[1] = y;
  26248. changed = true;
  26249. }
  26250. if (cache[2] !== z) {
  26251. cache[2] = z;
  26252. changed = true;
  26253. }
  26254. return changed;
  26255. };
  26256. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26257. var cache = this._valueCache[uniformName];
  26258. if (!cache) {
  26259. cache = [x, y, z, w];
  26260. this._valueCache[uniformName] = cache;
  26261. return true;
  26262. }
  26263. var changed = false;
  26264. if (cache[0] !== x) {
  26265. cache[0] = x;
  26266. changed = true;
  26267. }
  26268. if (cache[1] !== y) {
  26269. cache[1] = y;
  26270. changed = true;
  26271. }
  26272. if (cache[2] !== z) {
  26273. cache[2] = z;
  26274. changed = true;
  26275. }
  26276. if (cache[3] !== w) {
  26277. cache[3] = w;
  26278. changed = true;
  26279. }
  26280. return changed;
  26281. };
  26282. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  26283. var bufferName = this._uniformBuffersNames[name];
  26284. if (Effect._baseCache[bufferName] === buffer) {
  26285. return;
  26286. }
  26287. Effect._baseCache[bufferName] = buffer;
  26288. this._engine.bindUniformBufferBase(buffer, bufferName);
  26289. };
  26290. Effect.prototype.bindUniformBlock = function (blockName, index) {
  26291. this._engine.bindUniformBlock(this._program, blockName, index);
  26292. };
  26293. Effect.prototype.setIntArray = function (uniformName, array) {
  26294. this._valueCache[uniformName] = null;
  26295. this._engine.setIntArray(this.getUniform(uniformName), array);
  26296. return this;
  26297. };
  26298. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26299. this._valueCache[uniformName] = null;
  26300. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26301. return this;
  26302. };
  26303. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26304. this._valueCache[uniformName] = null;
  26305. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26306. return this;
  26307. };
  26308. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26309. this._valueCache[uniformName] = null;
  26310. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26311. return this;
  26312. };
  26313. Effect.prototype.setFloatArray = function (uniformName, array) {
  26314. this._valueCache[uniformName] = null;
  26315. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26316. return this;
  26317. };
  26318. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26319. this._valueCache[uniformName] = null;
  26320. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26321. return this;
  26322. };
  26323. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26324. this._valueCache[uniformName] = null;
  26325. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26326. return this;
  26327. };
  26328. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26329. this._valueCache[uniformName] = null;
  26330. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26331. return this;
  26332. };
  26333. Effect.prototype.setArray = function (uniformName, array) {
  26334. this._valueCache[uniformName] = null;
  26335. this._engine.setArray(this.getUniform(uniformName), array);
  26336. return this;
  26337. };
  26338. Effect.prototype.setArray2 = function (uniformName, array) {
  26339. this._valueCache[uniformName] = null;
  26340. this._engine.setArray2(this.getUniform(uniformName), array);
  26341. return this;
  26342. };
  26343. Effect.prototype.setArray3 = function (uniformName, array) {
  26344. this._valueCache[uniformName] = null;
  26345. this._engine.setArray3(this.getUniform(uniformName), array);
  26346. return this;
  26347. };
  26348. Effect.prototype.setArray4 = function (uniformName, array) {
  26349. this._valueCache[uniformName] = null;
  26350. this._engine.setArray4(this.getUniform(uniformName), array);
  26351. return this;
  26352. };
  26353. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26354. if (!matrices) {
  26355. return this;
  26356. }
  26357. this._valueCache[uniformName] = null;
  26358. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26359. return this;
  26360. };
  26361. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26362. if (this._cacheMatrix(uniformName, matrix)) {
  26363. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26364. }
  26365. return this;
  26366. };
  26367. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26368. this._valueCache[uniformName] = null;
  26369. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26370. return this;
  26371. };
  26372. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26373. this._valueCache[uniformName] = null;
  26374. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26375. return this;
  26376. };
  26377. Effect.prototype.setFloat = function (uniformName, value) {
  26378. var cache = this._valueCache[uniformName];
  26379. if (cache !== undefined && cache === value)
  26380. return this;
  26381. this._valueCache[uniformName] = value;
  26382. this._engine.setFloat(this.getUniform(uniformName), value);
  26383. return this;
  26384. };
  26385. Effect.prototype.setBool = function (uniformName, bool) {
  26386. var cache = this._valueCache[uniformName];
  26387. if (cache !== undefined && cache === bool)
  26388. return this;
  26389. this._valueCache[uniformName] = bool;
  26390. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26391. return this;
  26392. };
  26393. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26394. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26395. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26396. }
  26397. return this;
  26398. };
  26399. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26400. if (this._cacheFloat2(uniformName, x, y)) {
  26401. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26402. }
  26403. return this;
  26404. };
  26405. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26406. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26407. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26408. }
  26409. return this;
  26410. };
  26411. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26412. if (this._cacheFloat3(uniformName, x, y, z)) {
  26413. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26414. }
  26415. return this;
  26416. };
  26417. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26418. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26419. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26420. }
  26421. return this;
  26422. };
  26423. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26424. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26425. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26426. }
  26427. return this;
  26428. };
  26429. Effect.prototype.setColor3 = function (uniformName, color3) {
  26430. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26431. this._engine.setColor3(this.getUniform(uniformName), color3);
  26432. }
  26433. return this;
  26434. };
  26435. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26436. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26437. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26438. }
  26439. return this;
  26440. };
  26441. Effect.ResetCache = function () {
  26442. Effect._baseCache = {};
  26443. };
  26444. Effect._uniqueIdSeed = 0;
  26445. Effect._baseCache = {};
  26446. // Statics
  26447. Effect.ShadersStore = {};
  26448. Effect.IncludesShadersStore = {};
  26449. return Effect;
  26450. }());
  26451. BABYLON.Effect = Effect;
  26452. })(BABYLON || (BABYLON = {}));
  26453. //# sourceMappingURL=babylon.effect.js.map
  26454. var BABYLON;
  26455. (function (BABYLON) {
  26456. var MaterialHelper = /** @class */ (function () {
  26457. function MaterialHelper() {
  26458. }
  26459. MaterialHelper.BindEyePosition = function (effect, scene) {
  26460. if (scene._forcedViewPosition) {
  26461. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  26462. return;
  26463. }
  26464. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  26465. };
  26466. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  26467. defines._needUVs = true;
  26468. defines[key] = true;
  26469. if (texture.getTextureMatrix().isIdentity(true)) {
  26470. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  26471. if (texture.coordinatesIndex === 0) {
  26472. defines["MAINUV1"] = true;
  26473. }
  26474. else {
  26475. defines["MAINUV2"] = true;
  26476. }
  26477. }
  26478. else {
  26479. defines[key + "DIRECTUV"] = 0;
  26480. }
  26481. };
  26482. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  26483. var matrix = texture.getTextureMatrix();
  26484. if (!matrix.isIdentity(true)) {
  26485. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  26486. }
  26487. };
  26488. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  26489. if (defines._areMiscDirty) {
  26490. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  26491. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  26492. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  26493. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  26494. }
  26495. };
  26496. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  26497. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  26498. var changed = false;
  26499. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  26500. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  26501. changed = true;
  26502. }
  26503. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  26504. defines["ALPHATEST"] = !defines["ALPHATEST"];
  26505. changed = true;
  26506. }
  26507. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  26508. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  26509. changed = true;
  26510. }
  26511. if (defines["INSTANCES"] !== useInstances) {
  26512. defines["INSTANCES"] = useInstances;
  26513. changed = true;
  26514. }
  26515. if (changed) {
  26516. defines.markAsUnprocessed();
  26517. }
  26518. };
  26519. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  26520. if (useMorphTargets === void 0) { useMorphTargets = false; }
  26521. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  26522. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  26523. return false;
  26524. }
  26525. defines._normals = defines._needNormals;
  26526. defines._uvs = defines._needUVs;
  26527. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  26528. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26529. defines["TANGENT"] = true;
  26530. }
  26531. if (defines._needUVs) {
  26532. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  26533. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  26534. }
  26535. else {
  26536. defines["UV1"] = false;
  26537. defines["UV2"] = false;
  26538. }
  26539. if (useVertexColor) {
  26540. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  26541. defines["VERTEXCOLOR"] = hasVertexColors;
  26542. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  26543. }
  26544. if (useBones) {
  26545. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26546. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  26547. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  26548. }
  26549. else {
  26550. defines["NUM_BONE_INFLUENCERS"] = 0;
  26551. defines["BonesPerMesh"] = 0;
  26552. }
  26553. }
  26554. if (useMorphTargets) {
  26555. var manager = mesh.morphTargetManager;
  26556. if (manager) {
  26557. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  26558. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  26559. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  26560. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  26561. }
  26562. else {
  26563. defines["MORPHTARGETS_TANGENT"] = false;
  26564. defines["MORPHTARGETS_NORMAL"] = false;
  26565. defines["MORPHTARGETS"] = false;
  26566. defines["NUM_MORPH_INFLUENCERS"] = 0;
  26567. }
  26568. }
  26569. return true;
  26570. };
  26571. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  26572. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26573. if (disableLighting === void 0) { disableLighting = false; }
  26574. if (!defines._areLightsDirty) {
  26575. return defines._needNormals;
  26576. }
  26577. var lightIndex = 0;
  26578. var needNormals = false;
  26579. var needRebuild = false;
  26580. var lightmapMode = false;
  26581. var shadowEnabled = false;
  26582. var specularEnabled = false;
  26583. if (scene.lightsEnabled && !disableLighting) {
  26584. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26585. var light = _a[_i];
  26586. needNormals = true;
  26587. if (defines["LIGHT" + lightIndex] === undefined) {
  26588. needRebuild = true;
  26589. }
  26590. defines["LIGHT" + lightIndex] = true;
  26591. defines["SPOTLIGHT" + lightIndex] = false;
  26592. defines["HEMILIGHT" + lightIndex] = false;
  26593. defines["POINTLIGHT" + lightIndex] = false;
  26594. defines["DIRLIGHT" + lightIndex] = false;
  26595. var type;
  26596. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  26597. type = "SPOTLIGHT" + lightIndex;
  26598. }
  26599. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  26600. type = "HEMILIGHT" + lightIndex;
  26601. }
  26602. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  26603. type = "POINTLIGHT" + lightIndex;
  26604. }
  26605. else {
  26606. type = "DIRLIGHT" + lightIndex;
  26607. }
  26608. defines[type] = true;
  26609. // Specular
  26610. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  26611. specularEnabled = true;
  26612. }
  26613. // Shadows
  26614. defines["SHADOW" + lightIndex] = false;
  26615. defines["SHADOWPCF" + lightIndex] = false;
  26616. defines["SHADOWESM" + lightIndex] = false;
  26617. defines["SHADOWCUBE" + lightIndex] = false;
  26618. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  26619. var shadowGenerator = light.getShadowGenerator();
  26620. if (shadowGenerator) {
  26621. shadowEnabled = true;
  26622. shadowGenerator.prepareDefines(defines, lightIndex);
  26623. }
  26624. }
  26625. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26626. lightmapMode = true;
  26627. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26628. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  26629. }
  26630. else {
  26631. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  26632. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  26633. }
  26634. lightIndex++;
  26635. if (lightIndex === maxSimultaneousLights)
  26636. break;
  26637. }
  26638. }
  26639. defines["SPECULARTERM"] = specularEnabled;
  26640. defines["SHADOWS"] = shadowEnabled;
  26641. // Resetting all other lights if any
  26642. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  26643. if (defines["LIGHT" + index] !== undefined) {
  26644. defines["LIGHT" + index] = false;
  26645. defines["HEMILIGHT" + lightIndex] = false;
  26646. defines["POINTLIGHT" + lightIndex] = false;
  26647. defines["DIRLIGHT" + lightIndex] = false;
  26648. defines["SPOTLIGHT" + lightIndex] = false;
  26649. defines["SHADOW" + lightIndex] = false;
  26650. }
  26651. }
  26652. var caps = scene.getEngine().getCaps();
  26653. if (defines["SHADOWFLOAT"] === undefined) {
  26654. needRebuild = true;
  26655. }
  26656. defines["SHADOWFLOAT"] = shadowEnabled &&
  26657. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  26658. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  26659. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  26660. if (needRebuild) {
  26661. defines.rebuild();
  26662. }
  26663. return needNormals;
  26664. };
  26665. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  26666. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26667. var uniformsList;
  26668. var uniformBuffersList = null;
  26669. if (uniformsListOrOptions.uniformsNames) {
  26670. var options = uniformsListOrOptions;
  26671. uniformsList = options.uniformsNames;
  26672. uniformBuffersList = options.uniformBuffersNames;
  26673. samplersList = options.samplers;
  26674. defines = options.defines;
  26675. maxSimultaneousLights = options.maxSimultaneousLights;
  26676. }
  26677. else {
  26678. uniformsList = uniformsListOrOptions;
  26679. if (!samplersList) {
  26680. samplersList = [];
  26681. }
  26682. }
  26683. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26684. if (!defines["LIGHT" + lightIndex]) {
  26685. break;
  26686. }
  26687. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  26688. if (uniformBuffersList) {
  26689. uniformBuffersList.push("Light" + lightIndex);
  26690. }
  26691. samplersList.push("shadowSampler" + lightIndex);
  26692. }
  26693. if (defines["NUM_MORPH_INFLUENCERS"]) {
  26694. uniformsList.push("morphTargetInfluences");
  26695. }
  26696. };
  26697. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  26698. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26699. if (rank === void 0) { rank = 0; }
  26700. var lightFallbackRank = 0;
  26701. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26702. if (!defines["LIGHT" + lightIndex]) {
  26703. break;
  26704. }
  26705. if (lightIndex > 0) {
  26706. lightFallbackRank = rank + lightIndex;
  26707. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  26708. }
  26709. if (!defines["SHADOWS"]) {
  26710. if (defines["SHADOW" + lightIndex]) {
  26711. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  26712. }
  26713. if (defines["SHADOWPCF" + lightIndex]) {
  26714. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  26715. }
  26716. if (defines["SHADOWESM" + lightIndex]) {
  26717. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  26718. }
  26719. }
  26720. }
  26721. return lightFallbackRank++;
  26722. };
  26723. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  26724. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  26725. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  26726. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  26727. var manager = mesh.morphTargetManager;
  26728. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  26729. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  26730. for (var index = 0; index < influencers; index++) {
  26731. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  26732. if (normal) {
  26733. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  26734. }
  26735. if (tangent) {
  26736. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  26737. }
  26738. if (attribs.length > maxAttributesCount) {
  26739. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  26740. }
  26741. }
  26742. }
  26743. };
  26744. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26745. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26746. fallbacks.addCPUSkinningFallback(0, mesh);
  26747. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26748. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26749. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26750. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26751. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26752. }
  26753. }
  26754. };
  26755. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26756. if (defines["INSTANCES"]) {
  26757. attribs.push("world0");
  26758. attribs.push("world1");
  26759. attribs.push("world2");
  26760. attribs.push("world3");
  26761. }
  26762. };
  26763. // Bindings
  26764. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  26765. if (light.shadowEnabled && mesh.receiveShadows) {
  26766. var shadowGenerator = light.getShadowGenerator();
  26767. if (shadowGenerator) {
  26768. shadowGenerator.bindShadowLight(lightIndex, effect);
  26769. }
  26770. }
  26771. };
  26772. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26773. light.transferToEffect(effect, lightIndex + "");
  26774. };
  26775. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  26776. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26777. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  26778. var lightIndex = 0;
  26779. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  26780. var light = _a[_i];
  26781. var scaledIntensity = light.getScaledIntensity();
  26782. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  26783. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26784. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  26785. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  26786. if (defines["SPECULARTERM"]) {
  26787. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  26788. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  26789. }
  26790. // Shadows
  26791. if (scene.shadowsEnabled) {
  26792. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  26793. }
  26794. light._uniformBuffer.update();
  26795. lightIndex++;
  26796. if (lightIndex === maxSimultaneousLights)
  26797. break;
  26798. }
  26799. };
  26800. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26801. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26802. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26803. effect.setColor3("vFogColor", scene.fogColor);
  26804. }
  26805. };
  26806. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26807. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  26808. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26809. if (matrices && effect) {
  26810. effect.setMatrices("mBones", matrices);
  26811. }
  26812. }
  26813. };
  26814. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  26815. var manager = abstractMesh.morphTargetManager;
  26816. if (!abstractMesh || !manager) {
  26817. return;
  26818. }
  26819. effect.setFloatArray("morphTargetInfluences", manager.influences);
  26820. };
  26821. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26822. if (defines["LOGARITHMICDEPTH"]) {
  26823. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26824. }
  26825. };
  26826. MaterialHelper.BindClipPlane = function (effect, scene) {
  26827. if (scene.clipPlane) {
  26828. var clipPlane = scene.clipPlane;
  26829. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26830. }
  26831. };
  26832. return MaterialHelper;
  26833. }());
  26834. BABYLON.MaterialHelper = MaterialHelper;
  26835. })(BABYLON || (BABYLON = {}));
  26836. //# sourceMappingURL=babylon.materialHelper.js.map
  26837. var BABYLON;
  26838. (function (BABYLON) {
  26839. var MaterialDefines = /** @class */ (function () {
  26840. function MaterialDefines() {
  26841. this._isDirty = true;
  26842. this._areLightsDirty = true;
  26843. this._areAttributesDirty = true;
  26844. this._areTexturesDirty = true;
  26845. this._areFresnelDirty = true;
  26846. this._areMiscDirty = true;
  26847. this._areImageProcessingDirty = true;
  26848. this._normals = false;
  26849. this._uvs = false;
  26850. this._needNormals = false;
  26851. this._needUVs = false;
  26852. }
  26853. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  26854. get: function () {
  26855. return this._isDirty;
  26856. },
  26857. enumerable: true,
  26858. configurable: true
  26859. });
  26860. MaterialDefines.prototype.markAsProcessed = function () {
  26861. this._isDirty = false;
  26862. this._areAttributesDirty = false;
  26863. this._areTexturesDirty = false;
  26864. this._areFresnelDirty = false;
  26865. this._areLightsDirty = false;
  26866. this._areMiscDirty = false;
  26867. this._areImageProcessingDirty = false;
  26868. };
  26869. MaterialDefines.prototype.markAsUnprocessed = function () {
  26870. this._isDirty = true;
  26871. };
  26872. MaterialDefines.prototype.markAllAsDirty = function () {
  26873. this._areTexturesDirty = true;
  26874. this._areAttributesDirty = true;
  26875. this._areLightsDirty = true;
  26876. this._areFresnelDirty = true;
  26877. this._areMiscDirty = true;
  26878. this._areImageProcessingDirty = true;
  26879. this._isDirty = true;
  26880. };
  26881. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  26882. this._areImageProcessingDirty = true;
  26883. this._isDirty = true;
  26884. };
  26885. MaterialDefines.prototype.markAsLightDirty = function () {
  26886. this._areLightsDirty = true;
  26887. this._isDirty = true;
  26888. };
  26889. MaterialDefines.prototype.markAsAttributesDirty = function () {
  26890. this._areAttributesDirty = true;
  26891. this._isDirty = true;
  26892. };
  26893. MaterialDefines.prototype.markAsTexturesDirty = function () {
  26894. this._areTexturesDirty = true;
  26895. this._isDirty = true;
  26896. };
  26897. MaterialDefines.prototype.markAsFresnelDirty = function () {
  26898. this._areFresnelDirty = true;
  26899. this._isDirty = true;
  26900. };
  26901. MaterialDefines.prototype.markAsMiscDirty = function () {
  26902. this._areMiscDirty = true;
  26903. this._isDirty = true;
  26904. };
  26905. MaterialDefines.prototype.rebuild = function () {
  26906. if (this._keys) {
  26907. delete this._keys;
  26908. }
  26909. this._keys = [];
  26910. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  26911. var key = _a[_i];
  26912. if (key[0] === "_") {
  26913. continue;
  26914. }
  26915. this._keys.push(key);
  26916. }
  26917. };
  26918. MaterialDefines.prototype.isEqual = function (other) {
  26919. if (this._keys.length !== other._keys.length) {
  26920. return false;
  26921. }
  26922. for (var index = 0; index < this._keys.length; index++) {
  26923. var prop = this._keys[index];
  26924. if (this[prop] !== other[prop]) {
  26925. return false;
  26926. }
  26927. }
  26928. return true;
  26929. };
  26930. MaterialDefines.prototype.cloneTo = function (other) {
  26931. if (this._keys.length !== other._keys.length) {
  26932. other._keys = this._keys.slice(0);
  26933. }
  26934. for (var index = 0; index < this._keys.length; index++) {
  26935. var prop = this._keys[index];
  26936. other[prop] = this[prop];
  26937. }
  26938. };
  26939. MaterialDefines.prototype.reset = function () {
  26940. for (var index = 0; index < this._keys.length; index++) {
  26941. var prop = this._keys[index];
  26942. if (typeof (this[prop]) === "number") {
  26943. this[prop] = 0;
  26944. }
  26945. else {
  26946. this[prop] = false;
  26947. }
  26948. }
  26949. };
  26950. MaterialDefines.prototype.toString = function () {
  26951. var result = "";
  26952. for (var index = 0; index < this._keys.length; index++) {
  26953. var prop = this._keys[index];
  26954. var value = this[prop];
  26955. if (typeof (value) === "number") {
  26956. result += "#define " + prop + " " + this[prop] + "\n";
  26957. }
  26958. else if (value) {
  26959. result += "#define " + prop + "\n";
  26960. }
  26961. }
  26962. return result;
  26963. };
  26964. return MaterialDefines;
  26965. }());
  26966. BABYLON.MaterialDefines = MaterialDefines;
  26967. var Material = /** @class */ (function () {
  26968. function Material(name, scene, doNotAdd) {
  26969. this.checkReadyOnEveryCall = false;
  26970. this.checkReadyOnlyOnce = false;
  26971. this.state = "";
  26972. this.alpha = 1.0;
  26973. this._backFaceCulling = true;
  26974. this.doNotSerialize = false;
  26975. this.storeEffectOnSubMeshes = false;
  26976. /**
  26977. * An event triggered when the material is disposed.
  26978. * @type {BABYLON.Observable}
  26979. */
  26980. this.onDisposeObservable = new BABYLON.Observable();
  26981. /**
  26982. * An event triggered when the material is bound.
  26983. * @type {BABYLON.Observable}
  26984. */
  26985. this.onBindObservable = new BABYLON.Observable();
  26986. /**
  26987. * An event triggered when the material is unbound.
  26988. * @type {BABYLON.Observable}
  26989. */
  26990. this.onUnBindObservable = new BABYLON.Observable();
  26991. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26992. this._needDepthPrePass = false;
  26993. this.disableDepthWrite = false;
  26994. this.forceDepthWrite = false;
  26995. this.separateCullingPass = false;
  26996. this._fogEnabled = true;
  26997. this.pointSize = 1.0;
  26998. this.zOffset = 0;
  26999. this._wasPreviouslyReady = false;
  27000. this._fillMode = Material.TriangleFillMode;
  27001. this.name = name;
  27002. this.id = name || BABYLON.Tools.RandomId();
  27003. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27004. if (this._scene.useRightHandedSystem) {
  27005. this.sideOrientation = Material.ClockWiseSideOrientation;
  27006. }
  27007. else {
  27008. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27009. }
  27010. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27011. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27012. if (!doNotAdd) {
  27013. this._scene.materials.push(this);
  27014. }
  27015. }
  27016. Object.defineProperty(Material, "TriangleFillMode", {
  27017. get: function () {
  27018. return Material._TriangleFillMode;
  27019. },
  27020. enumerable: true,
  27021. configurable: true
  27022. });
  27023. Object.defineProperty(Material, "WireFrameFillMode", {
  27024. get: function () {
  27025. return Material._WireFrameFillMode;
  27026. },
  27027. enumerable: true,
  27028. configurable: true
  27029. });
  27030. Object.defineProperty(Material, "PointFillMode", {
  27031. get: function () {
  27032. return Material._PointFillMode;
  27033. },
  27034. enumerable: true,
  27035. configurable: true
  27036. });
  27037. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27038. get: function () {
  27039. return Material._ClockWiseSideOrientation;
  27040. },
  27041. enumerable: true,
  27042. configurable: true
  27043. });
  27044. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27045. get: function () {
  27046. return Material._CounterClockWiseSideOrientation;
  27047. },
  27048. enumerable: true,
  27049. configurable: true
  27050. });
  27051. Object.defineProperty(Material, "TextureDirtyFlag", {
  27052. get: function () {
  27053. return Material._TextureDirtyFlag;
  27054. },
  27055. enumerable: true,
  27056. configurable: true
  27057. });
  27058. Object.defineProperty(Material, "LightDirtyFlag", {
  27059. get: function () {
  27060. return Material._LightDirtyFlag;
  27061. },
  27062. enumerable: true,
  27063. configurable: true
  27064. });
  27065. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27066. get: function () {
  27067. return Material._FresnelDirtyFlag;
  27068. },
  27069. enumerable: true,
  27070. configurable: true
  27071. });
  27072. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27073. get: function () {
  27074. return Material._AttributesDirtyFlag;
  27075. },
  27076. enumerable: true,
  27077. configurable: true
  27078. });
  27079. Object.defineProperty(Material, "MiscDirtyFlag", {
  27080. get: function () {
  27081. return Material._MiscDirtyFlag;
  27082. },
  27083. enumerable: true,
  27084. configurable: true
  27085. });
  27086. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27087. get: function () {
  27088. return this._backFaceCulling;
  27089. },
  27090. set: function (value) {
  27091. if (this._backFaceCulling === value) {
  27092. return;
  27093. }
  27094. this._backFaceCulling = value;
  27095. this.markAsDirty(Material.TextureDirtyFlag);
  27096. },
  27097. enumerable: true,
  27098. configurable: true
  27099. });
  27100. Object.defineProperty(Material.prototype, "onDispose", {
  27101. set: function (callback) {
  27102. if (this._onDisposeObserver) {
  27103. this.onDisposeObservable.remove(this._onDisposeObserver);
  27104. }
  27105. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27106. },
  27107. enumerable: true,
  27108. configurable: true
  27109. });
  27110. Object.defineProperty(Material.prototype, "onBind", {
  27111. set: function (callback) {
  27112. if (this._onBindObserver) {
  27113. this.onBindObservable.remove(this._onBindObserver);
  27114. }
  27115. this._onBindObserver = this.onBindObservable.add(callback);
  27116. },
  27117. enumerable: true,
  27118. configurable: true
  27119. });
  27120. Object.defineProperty(Material.prototype, "alphaMode", {
  27121. get: function () {
  27122. return this._alphaMode;
  27123. },
  27124. set: function (value) {
  27125. if (this._alphaMode === value) {
  27126. return;
  27127. }
  27128. this._alphaMode = value;
  27129. this.markAsDirty(Material.TextureDirtyFlag);
  27130. },
  27131. enumerable: true,
  27132. configurable: true
  27133. });
  27134. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27135. get: function () {
  27136. return this._needDepthPrePass;
  27137. },
  27138. set: function (value) {
  27139. if (this._needDepthPrePass === value) {
  27140. return;
  27141. }
  27142. this._needDepthPrePass = value;
  27143. if (this._needDepthPrePass) {
  27144. this.checkReadyOnEveryCall = true;
  27145. }
  27146. },
  27147. enumerable: true,
  27148. configurable: true
  27149. });
  27150. Object.defineProperty(Material.prototype, "fogEnabled", {
  27151. get: function () {
  27152. return this._fogEnabled;
  27153. },
  27154. set: function (value) {
  27155. if (this._fogEnabled === value) {
  27156. return;
  27157. }
  27158. this._fogEnabled = value;
  27159. this.markAsDirty(Material.MiscDirtyFlag);
  27160. },
  27161. enumerable: true,
  27162. configurable: true
  27163. });
  27164. Object.defineProperty(Material.prototype, "wireframe", {
  27165. get: function () {
  27166. return this._fillMode === Material.WireFrameFillMode;
  27167. },
  27168. set: function (value) {
  27169. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27170. },
  27171. enumerable: true,
  27172. configurable: true
  27173. });
  27174. Object.defineProperty(Material.prototype, "pointsCloud", {
  27175. get: function () {
  27176. return this._fillMode === Material.PointFillMode;
  27177. },
  27178. set: function (value) {
  27179. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27180. },
  27181. enumerable: true,
  27182. configurable: true
  27183. });
  27184. Object.defineProperty(Material.prototype, "fillMode", {
  27185. get: function () {
  27186. return this._fillMode;
  27187. },
  27188. set: function (value) {
  27189. if (this._fillMode === value) {
  27190. return;
  27191. }
  27192. this._fillMode = value;
  27193. this.markAsDirty(Material.MiscDirtyFlag);
  27194. },
  27195. enumerable: true,
  27196. configurable: true
  27197. });
  27198. /**
  27199. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27200. * subclasses should override adding information pertainent to themselves
  27201. */
  27202. Material.prototype.toString = function (fullDetails) {
  27203. var ret = "Name: " + this.name;
  27204. if (fullDetails) {
  27205. }
  27206. return ret;
  27207. };
  27208. /**
  27209. * Child classes can use it to update shaders
  27210. */
  27211. Material.prototype.getClassName = function () {
  27212. return "Material";
  27213. };
  27214. Object.defineProperty(Material.prototype, "isFrozen", {
  27215. get: function () {
  27216. return this.checkReadyOnlyOnce;
  27217. },
  27218. enumerable: true,
  27219. configurable: true
  27220. });
  27221. Material.prototype.freeze = function () {
  27222. this.checkReadyOnlyOnce = true;
  27223. };
  27224. Material.prototype.unfreeze = function () {
  27225. this.checkReadyOnlyOnce = false;
  27226. };
  27227. Material.prototype.isReady = function (mesh, useInstances) {
  27228. return true;
  27229. };
  27230. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27231. return false;
  27232. };
  27233. Material.prototype.getEffect = function () {
  27234. return this._effect;
  27235. };
  27236. Material.prototype.getScene = function () {
  27237. return this._scene;
  27238. };
  27239. Material.prototype.needAlphaBlending = function () {
  27240. return (this.alpha < 1.0);
  27241. };
  27242. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  27243. return (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  27244. };
  27245. Material.prototype.needAlphaTesting = function () {
  27246. return false;
  27247. };
  27248. Material.prototype.getAlphaTestTexture = function () {
  27249. return null;
  27250. };
  27251. Material.prototype.markDirty = function () {
  27252. this._wasPreviouslyReady = false;
  27253. };
  27254. Material.prototype._preBind = function (effect, overrideOrientation) {
  27255. if (overrideOrientation === void 0) { overrideOrientation = null; }
  27256. var engine = this._scene.getEngine();
  27257. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  27258. var reverse = orientation === Material.ClockWiseSideOrientation;
  27259. engine.enableEffect(effect ? effect : this._effect);
  27260. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27261. return reverse;
  27262. };
  27263. Material.prototype.bind = function (world, mesh) {
  27264. };
  27265. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27266. };
  27267. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27268. };
  27269. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  27270. sceneUbo.bindToEffect(effect, "Scene");
  27271. };
  27272. Material.prototype.bindView = function (effect) {
  27273. if (!this._useUBO) {
  27274. effect.setMatrix("view", this.getScene().getViewMatrix());
  27275. }
  27276. else {
  27277. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27278. }
  27279. };
  27280. Material.prototype.bindViewProjection = function (effect) {
  27281. if (!this._useUBO) {
  27282. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  27283. }
  27284. else {
  27285. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  27286. }
  27287. };
  27288. Material.prototype._afterBind = function (mesh) {
  27289. this._scene._cachedMaterial = this;
  27290. if (mesh) {
  27291. this._scene._cachedVisibility = mesh.visibility;
  27292. }
  27293. else {
  27294. this._scene._cachedVisibility = 1;
  27295. }
  27296. if (mesh) {
  27297. this.onBindObservable.notifyObservers(mesh);
  27298. }
  27299. if (this.disableDepthWrite) {
  27300. var engine = this._scene.getEngine();
  27301. this._cachedDepthWriteState = engine.getDepthWrite();
  27302. engine.setDepthWrite(false);
  27303. }
  27304. };
  27305. Material.prototype.unbind = function () {
  27306. this.onUnBindObservable.notifyObservers(this);
  27307. if (this.disableDepthWrite) {
  27308. var engine = this._scene.getEngine();
  27309. engine.setDepthWrite(this._cachedDepthWriteState);
  27310. }
  27311. };
  27312. Material.prototype.getActiveTextures = function () {
  27313. return [];
  27314. };
  27315. Material.prototype.hasTexture = function (texture) {
  27316. return false;
  27317. };
  27318. Material.prototype.clone = function (name) {
  27319. return null;
  27320. };
  27321. Material.prototype.getBindedMeshes = function () {
  27322. var result = new Array();
  27323. for (var index = 0; index < this._scene.meshes.length; index++) {
  27324. var mesh = this._scene.meshes[index];
  27325. if (mesh.material === this) {
  27326. result.push(mesh);
  27327. }
  27328. }
  27329. return result;
  27330. };
  27331. /**
  27332. * Force shader compilation including textures ready check
  27333. */
  27334. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  27335. var _this = this;
  27336. var subMesh = new BABYLON.BaseSubMesh();
  27337. var scene = this.getScene();
  27338. var engine = scene.getEngine();
  27339. var checkReady = function () {
  27340. if (!_this._scene || !_this._scene.getEngine()) {
  27341. return;
  27342. }
  27343. if (subMesh._materialDefines) {
  27344. subMesh._materialDefines._renderId = -1;
  27345. }
  27346. var alphaTestState = engine.getAlphaTesting();
  27347. var clipPlaneState = scene.clipPlane;
  27348. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  27349. if (options && options.clipPlane) {
  27350. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  27351. }
  27352. if (_this.storeEffectOnSubMeshes) {
  27353. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  27354. if (onCompiled) {
  27355. onCompiled(_this);
  27356. }
  27357. }
  27358. else {
  27359. setTimeout(checkReady, 16);
  27360. }
  27361. }
  27362. else {
  27363. if (_this.isReady(mesh)) {
  27364. if (onCompiled) {
  27365. onCompiled(_this);
  27366. }
  27367. }
  27368. else {
  27369. setTimeout(checkReady, 16);
  27370. }
  27371. }
  27372. engine.setAlphaTesting(alphaTestState);
  27373. if (options && options.clipPlane) {
  27374. scene.clipPlane = clipPlaneState;
  27375. }
  27376. };
  27377. checkReady();
  27378. };
  27379. Material.prototype.markAsDirty = function (flag) {
  27380. if (flag & Material.TextureDirtyFlag) {
  27381. this._markAllSubMeshesAsTexturesDirty();
  27382. }
  27383. if (flag & Material.LightDirtyFlag) {
  27384. this._markAllSubMeshesAsLightsDirty();
  27385. }
  27386. if (flag & Material.FresnelDirtyFlag) {
  27387. this._markAllSubMeshesAsFresnelDirty();
  27388. }
  27389. if (flag & Material.AttributesDirtyFlag) {
  27390. this._markAllSubMeshesAsAttributesDirty();
  27391. }
  27392. if (flag & Material.MiscDirtyFlag) {
  27393. this._markAllSubMeshesAsMiscDirty();
  27394. }
  27395. this.getScene().resetCachedMaterial();
  27396. };
  27397. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  27398. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  27399. var mesh = _a[_i];
  27400. if (!mesh.subMeshes) {
  27401. continue;
  27402. }
  27403. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  27404. var subMesh = _c[_b];
  27405. if (subMesh.getMaterial() !== this) {
  27406. continue;
  27407. }
  27408. if (!subMesh._materialDefines) {
  27409. continue;
  27410. }
  27411. func(subMesh._materialDefines);
  27412. }
  27413. }
  27414. };
  27415. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  27416. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  27417. };
  27418. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  27419. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  27420. };
  27421. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  27422. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  27423. };
  27424. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  27425. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  27426. };
  27427. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  27428. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  27429. };
  27430. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  27431. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  27432. };
  27433. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27434. // Animations
  27435. this.getScene().stopAnimation(this);
  27436. // Remove from scene
  27437. var index = this._scene.materials.indexOf(this);
  27438. if (index >= 0) {
  27439. this._scene.materials.splice(index, 1);
  27440. }
  27441. // Remove from meshes
  27442. for (index = 0; index < this._scene.meshes.length; index++) {
  27443. var mesh = this._scene.meshes[index];
  27444. if (mesh.material === this) {
  27445. mesh.material = null;
  27446. if (mesh.geometry) {
  27447. var geometry = (mesh.geometry);
  27448. if (this.storeEffectOnSubMeshes) {
  27449. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  27450. var subMesh = _a[_i];
  27451. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  27452. if (forceDisposeEffect && subMesh._materialEffect) {
  27453. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  27454. }
  27455. }
  27456. }
  27457. else {
  27458. geometry._releaseVertexArrayObject(this._effect);
  27459. }
  27460. }
  27461. }
  27462. }
  27463. this._uniformBuffer.dispose();
  27464. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27465. if (forceDisposeEffect && this._effect) {
  27466. if (!this.storeEffectOnSubMeshes) {
  27467. this._scene.getEngine()._releaseEffect(this._effect);
  27468. }
  27469. this._effect = null;
  27470. }
  27471. // Callback
  27472. this.onDisposeObservable.notifyObservers(this);
  27473. this.onDisposeObservable.clear();
  27474. this.onBindObservable.clear();
  27475. this.onUnBindObservable.clear();
  27476. };
  27477. Material.prototype.serialize = function () {
  27478. return BABYLON.SerializationHelper.Serialize(this);
  27479. };
  27480. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27481. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27482. multiMaterial.id = parsedMultiMaterial.id;
  27483. if (BABYLON.Tags) {
  27484. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27485. }
  27486. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27487. var subMatId = parsedMultiMaterial.materials[matIndex];
  27488. if (subMatId) {
  27489. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27490. }
  27491. else {
  27492. multiMaterial.subMaterials.push(null);
  27493. }
  27494. }
  27495. return multiMaterial;
  27496. };
  27497. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27498. if (!parsedMaterial.customType) {
  27499. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27500. }
  27501. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  27502. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  27503. if (!BABYLON.LegacyPBRMaterial) {
  27504. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  27505. return;
  27506. }
  27507. }
  27508. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27509. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27510. ;
  27511. };
  27512. Material._TriangleFillMode = 0;
  27513. Material._WireFrameFillMode = 1;
  27514. Material._PointFillMode = 2;
  27515. Material._ClockWiseSideOrientation = 0;
  27516. Material._CounterClockWiseSideOrientation = 1;
  27517. Material._TextureDirtyFlag = 1;
  27518. Material._LightDirtyFlag = 2;
  27519. Material._FresnelDirtyFlag = 4;
  27520. Material._AttributesDirtyFlag = 8;
  27521. Material._MiscDirtyFlag = 16;
  27522. __decorate([
  27523. BABYLON.serialize()
  27524. ], Material.prototype, "id", void 0);
  27525. __decorate([
  27526. BABYLON.serialize()
  27527. ], Material.prototype, "name", void 0);
  27528. __decorate([
  27529. BABYLON.serialize()
  27530. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27531. __decorate([
  27532. BABYLON.serialize()
  27533. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27534. __decorate([
  27535. BABYLON.serialize()
  27536. ], Material.prototype, "state", void 0);
  27537. __decorate([
  27538. BABYLON.serialize()
  27539. ], Material.prototype, "alpha", void 0);
  27540. __decorate([
  27541. BABYLON.serialize("backFaceCulling")
  27542. ], Material.prototype, "_backFaceCulling", void 0);
  27543. __decorate([
  27544. BABYLON.serialize()
  27545. ], Material.prototype, "sideOrientation", void 0);
  27546. __decorate([
  27547. BABYLON.serialize("alphaMode")
  27548. ], Material.prototype, "_alphaMode", void 0);
  27549. __decorate([
  27550. BABYLON.serialize()
  27551. ], Material.prototype, "_needDepthPrePass", void 0);
  27552. __decorate([
  27553. BABYLON.serialize()
  27554. ], Material.prototype, "disableDepthWrite", void 0);
  27555. __decorate([
  27556. BABYLON.serialize()
  27557. ], Material.prototype, "forceDepthWrite", void 0);
  27558. __decorate([
  27559. BABYLON.serialize()
  27560. ], Material.prototype, "separateCullingPass", void 0);
  27561. __decorate([
  27562. BABYLON.serialize("fogEnabled")
  27563. ], Material.prototype, "_fogEnabled", void 0);
  27564. __decorate([
  27565. BABYLON.serialize()
  27566. ], Material.prototype, "pointSize", void 0);
  27567. __decorate([
  27568. BABYLON.serialize()
  27569. ], Material.prototype, "zOffset", void 0);
  27570. __decorate([
  27571. BABYLON.serialize()
  27572. ], Material.prototype, "wireframe", null);
  27573. __decorate([
  27574. BABYLON.serialize()
  27575. ], Material.prototype, "pointsCloud", null);
  27576. __decorate([
  27577. BABYLON.serialize()
  27578. ], Material.prototype, "fillMode", null);
  27579. return Material;
  27580. }());
  27581. BABYLON.Material = Material;
  27582. })(BABYLON || (BABYLON = {}));
  27583. //# sourceMappingURL=babylon.material.js.map
  27584. var BABYLON;
  27585. (function (BABYLON) {
  27586. var UniformBuffer = /** @class */ (function () {
  27587. /**
  27588. * Uniform buffer objects.
  27589. *
  27590. * Handles blocks of uniform on the GPU.
  27591. *
  27592. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  27593. *
  27594. * For more information, please refer to :
  27595. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  27596. */
  27597. function UniformBuffer(engine, data, dynamic) {
  27598. this._engine = engine;
  27599. this._noUBO = !engine.supportsUniformBuffers;
  27600. this._dynamic = dynamic;
  27601. this._data = data || [];
  27602. this._uniformLocations = {};
  27603. this._uniformSizes = {};
  27604. this._uniformLocationPointer = 0;
  27605. this._needSync = false;
  27606. if (this._noUBO) {
  27607. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  27608. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  27609. this.updateFloat = this._updateFloatForEffect;
  27610. this.updateFloat2 = this._updateFloat2ForEffect;
  27611. this.updateFloat3 = this._updateFloat3ForEffect;
  27612. this.updateFloat4 = this._updateFloat4ForEffect;
  27613. this.updateMatrix = this._updateMatrixForEffect;
  27614. this.updateVector3 = this._updateVector3ForEffect;
  27615. this.updateVector4 = this._updateVector4ForEffect;
  27616. this.updateColor3 = this._updateColor3ForEffect;
  27617. this.updateColor4 = this._updateColor4ForEffect;
  27618. }
  27619. else {
  27620. this._engine._uniformBuffers.push(this);
  27621. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  27622. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  27623. this.updateFloat = this._updateFloatForUniform;
  27624. this.updateFloat2 = this._updateFloat2ForUniform;
  27625. this.updateFloat3 = this._updateFloat3ForUniform;
  27626. this.updateFloat4 = this._updateFloat4ForUniform;
  27627. this.updateMatrix = this._updateMatrixForUniform;
  27628. this.updateVector3 = this._updateVector3ForUniform;
  27629. this.updateVector4 = this._updateVector4ForUniform;
  27630. this.updateColor3 = this._updateColor3ForUniform;
  27631. this.updateColor4 = this._updateColor4ForUniform;
  27632. }
  27633. }
  27634. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  27635. // Properties
  27636. /**
  27637. * Indicates if the buffer is using the WebGL2 UBO implementation,
  27638. * or just falling back on setUniformXXX calls.
  27639. */
  27640. get: function () {
  27641. return !this._noUBO;
  27642. },
  27643. enumerable: true,
  27644. configurable: true
  27645. });
  27646. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  27647. /**
  27648. * Indicates if the WebGL underlying uniform buffer is in sync
  27649. * with the javascript cache data.
  27650. */
  27651. get: function () {
  27652. return !this._needSync;
  27653. },
  27654. enumerable: true,
  27655. configurable: true
  27656. });
  27657. /**
  27658. * Indicates if the WebGL underlying uniform buffer is dynamic.
  27659. * Also, a dynamic UniformBuffer will disable cache verification and always
  27660. * update the underlying WebGL uniform buffer to the GPU.
  27661. */
  27662. UniformBuffer.prototype.isDynamic = function () {
  27663. return this._dynamic !== undefined;
  27664. };
  27665. /**
  27666. * The data cache on JS side.
  27667. */
  27668. UniformBuffer.prototype.getData = function () {
  27669. return this._bufferData;
  27670. };
  27671. /**
  27672. * The underlying WebGL Uniform buffer.
  27673. */
  27674. UniformBuffer.prototype.getBuffer = function () {
  27675. return this._buffer;
  27676. };
  27677. /**
  27678. * std140 layout specifies how to align data within an UBO structure.
  27679. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  27680. * for specs.
  27681. */
  27682. UniformBuffer.prototype._fillAlignment = function (size) {
  27683. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  27684. // and 4x4 matrices
  27685. // TODO : change if other types are used
  27686. var alignment;
  27687. if (size <= 2) {
  27688. alignment = size;
  27689. }
  27690. else {
  27691. alignment = 4;
  27692. }
  27693. if ((this._uniformLocationPointer % alignment) !== 0) {
  27694. var oldPointer = this._uniformLocationPointer;
  27695. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  27696. var diff = this._uniformLocationPointer - oldPointer;
  27697. for (var i = 0; i < diff; i++) {
  27698. this._data.push(0);
  27699. }
  27700. }
  27701. };
  27702. /**
  27703. * Adds an uniform in the buffer.
  27704. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  27705. * for the layout to be correct !
  27706. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27707. * @param {number|number[]} size Data size, or data directly.
  27708. */
  27709. UniformBuffer.prototype.addUniform = function (name, size) {
  27710. if (this._noUBO) {
  27711. return;
  27712. }
  27713. if (this._uniformLocations[name] !== undefined) {
  27714. // Already existing uniform
  27715. return;
  27716. }
  27717. // This function must be called in the order of the shader layout !
  27718. // size can be the size of the uniform, or data directly
  27719. var data;
  27720. if (size instanceof Array) {
  27721. data = size;
  27722. size = data.length;
  27723. }
  27724. else {
  27725. size = size;
  27726. data = [];
  27727. // Fill with zeros
  27728. for (var i = 0; i < size; i++) {
  27729. data.push(0);
  27730. }
  27731. }
  27732. this._fillAlignment(size);
  27733. this._uniformSizes[name] = size;
  27734. this._uniformLocations[name] = this._uniformLocationPointer;
  27735. this._uniformLocationPointer += size;
  27736. for (var i = 0; i < size; i++) {
  27737. this._data.push(data[i]);
  27738. }
  27739. this._needSync = true;
  27740. };
  27741. /**
  27742. * Wrapper for addUniform.
  27743. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27744. * @param {Matrix} mat A 4x4 matrix.
  27745. */
  27746. UniformBuffer.prototype.addMatrix = function (name, mat) {
  27747. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  27748. };
  27749. /**
  27750. * Wrapper for addUniform.
  27751. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27752. * @param {number} x
  27753. * @param {number} y
  27754. */
  27755. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  27756. var temp = [x, y];
  27757. this.addUniform(name, temp);
  27758. };
  27759. /**
  27760. * Wrapper for addUniform.
  27761. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27762. * @param {number} x
  27763. * @param {number} y
  27764. * @param {number} z
  27765. */
  27766. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  27767. var temp = [x, y, z];
  27768. this.addUniform(name, temp);
  27769. };
  27770. /**
  27771. * Wrapper for addUniform.
  27772. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27773. * @param {Color3} color
  27774. */
  27775. UniformBuffer.prototype.addColor3 = function (name, color) {
  27776. var temp = new Array();
  27777. color.toArray(temp);
  27778. this.addUniform(name, temp);
  27779. };
  27780. /**
  27781. * Wrapper for addUniform.
  27782. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27783. * @param {Color3} color
  27784. * @param {number} alpha
  27785. */
  27786. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  27787. var temp = new Array();
  27788. color.toArray(temp);
  27789. temp.push(alpha);
  27790. this.addUniform(name, temp);
  27791. };
  27792. /**
  27793. * Wrapper for addUniform.
  27794. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27795. * @param {Vector3} vector
  27796. */
  27797. UniformBuffer.prototype.addVector3 = function (name, vector) {
  27798. var temp = new Array();
  27799. vector.toArray(temp);
  27800. this.addUniform(name, temp);
  27801. };
  27802. /**
  27803. * Wrapper for addUniform.
  27804. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27805. */
  27806. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  27807. this.addUniform(name, 12);
  27808. };
  27809. /**
  27810. * Wrapper for addUniform.
  27811. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  27812. */
  27813. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  27814. this.addUniform(name, 8);
  27815. };
  27816. /**
  27817. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  27818. */
  27819. UniformBuffer.prototype.create = function () {
  27820. if (this._noUBO) {
  27821. return;
  27822. }
  27823. if (this._buffer) {
  27824. return; // nothing to do
  27825. }
  27826. // See spec, alignment must be filled as a vec4
  27827. this._fillAlignment(4);
  27828. this._bufferData = new Float32Array(this._data);
  27829. this._rebuild();
  27830. this._needSync = true;
  27831. };
  27832. UniformBuffer.prototype._rebuild = function () {
  27833. if (this._noUBO) {
  27834. return;
  27835. }
  27836. if (this._dynamic) {
  27837. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  27838. }
  27839. else {
  27840. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  27841. }
  27842. };
  27843. /**
  27844. * Updates the WebGL Uniform Buffer on the GPU.
  27845. * If the `dynamic` flag is set to true, no cache comparison is done.
  27846. * Otherwise, the buffer will be updated only if the cache differs.
  27847. */
  27848. UniformBuffer.prototype.update = function () {
  27849. if (!this._buffer) {
  27850. this.create();
  27851. return;
  27852. }
  27853. if (!this._dynamic && !this._needSync) {
  27854. return;
  27855. }
  27856. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  27857. this._needSync = false;
  27858. };
  27859. /**
  27860. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  27861. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  27862. * @param {number[]|Float32Array} data Flattened data
  27863. * @param {number} size Size of the data.
  27864. */
  27865. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  27866. var location = this._uniformLocations[uniformName];
  27867. if (location === undefined) {
  27868. if (this._buffer) {
  27869. // Cannot add an uniform if the buffer is already created
  27870. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  27871. return;
  27872. }
  27873. this.addUniform(uniformName, size);
  27874. location = this._uniformLocations[uniformName];
  27875. }
  27876. if (!this._buffer) {
  27877. this.create();
  27878. }
  27879. if (!this._dynamic) {
  27880. // Cache for static uniform buffers
  27881. var changed = false;
  27882. for (var i = 0; i < size; i++) {
  27883. if (this._bufferData[location + i] !== data[i]) {
  27884. changed = true;
  27885. this._bufferData[location + i] = data[i];
  27886. }
  27887. }
  27888. this._needSync = this._needSync || changed;
  27889. }
  27890. else {
  27891. // No cache for dynamic
  27892. for (var i = 0; i < size; i++) {
  27893. this._bufferData[location + i] = data[i];
  27894. }
  27895. }
  27896. };
  27897. // Update methods
  27898. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  27899. // To match std140, matrix must be realigned
  27900. for (var i = 0; i < 3; i++) {
  27901. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  27902. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  27903. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  27904. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27905. }
  27906. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  27907. };
  27908. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  27909. this._currentEffect.setMatrix3x3(name, matrix);
  27910. };
  27911. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  27912. this._currentEffect.setMatrix2x2(name, matrix);
  27913. };
  27914. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  27915. // To match std140, matrix must be realigned
  27916. for (var i = 0; i < 2; i++) {
  27917. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  27918. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  27919. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  27920. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  27921. }
  27922. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  27923. };
  27924. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  27925. this._currentEffect.setFloat(name, x);
  27926. };
  27927. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  27928. UniformBuffer._tempBuffer[0] = x;
  27929. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  27930. };
  27931. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  27932. if (suffix === void 0) { suffix = ""; }
  27933. this._currentEffect.setFloat2(name + suffix, x, y);
  27934. };
  27935. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  27936. if (suffix === void 0) { suffix = ""; }
  27937. UniformBuffer._tempBuffer[0] = x;
  27938. UniformBuffer._tempBuffer[1] = y;
  27939. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  27940. };
  27941. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  27942. if (suffix === void 0) { suffix = ""; }
  27943. this._currentEffect.setFloat3(name + suffix, x, y, z);
  27944. };
  27945. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  27946. if (suffix === void 0) { suffix = ""; }
  27947. UniformBuffer._tempBuffer[0] = x;
  27948. UniformBuffer._tempBuffer[1] = y;
  27949. UniformBuffer._tempBuffer[2] = z;
  27950. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27951. };
  27952. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  27953. if (suffix === void 0) { suffix = ""; }
  27954. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  27955. };
  27956. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  27957. if (suffix === void 0) { suffix = ""; }
  27958. UniformBuffer._tempBuffer[0] = x;
  27959. UniformBuffer._tempBuffer[1] = y;
  27960. UniformBuffer._tempBuffer[2] = z;
  27961. UniformBuffer._tempBuffer[3] = w;
  27962. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27963. };
  27964. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  27965. this._currentEffect.setMatrix(name, mat);
  27966. };
  27967. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  27968. this.updateUniform(name, mat.toArray(), 16);
  27969. };
  27970. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  27971. this._currentEffect.setVector3(name, vector);
  27972. };
  27973. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  27974. vector.toArray(UniformBuffer._tempBuffer);
  27975. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27976. };
  27977. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  27978. this._currentEffect.setVector4(name, vector);
  27979. };
  27980. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  27981. vector.toArray(UniformBuffer._tempBuffer);
  27982. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  27983. };
  27984. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  27985. if (suffix === void 0) { suffix = ""; }
  27986. this._currentEffect.setColor3(name + suffix, color);
  27987. };
  27988. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  27989. if (suffix === void 0) { suffix = ""; }
  27990. color.toArray(UniformBuffer._tempBuffer);
  27991. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  27992. };
  27993. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  27994. if (suffix === void 0) { suffix = ""; }
  27995. this._currentEffect.setColor4(name + suffix, color, alpha);
  27996. };
  27997. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  27998. if (suffix === void 0) { suffix = ""; }
  27999. color.toArray(UniformBuffer._tempBuffer);
  28000. UniformBuffer._tempBuffer[3] = alpha;
  28001. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28002. };
  28003. /**
  28004. * Sets a sampler uniform on the effect.
  28005. * @param {string} name Name of the sampler.
  28006. * @param {Texture} texture
  28007. */
  28008. UniformBuffer.prototype.setTexture = function (name, texture) {
  28009. this._currentEffect.setTexture(name, texture);
  28010. };
  28011. /**
  28012. * Directly updates the value of the uniform in the cache AND on the GPU.
  28013. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28014. * @param {number[]|Float32Array} data Flattened data
  28015. */
  28016. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28017. this.updateUniform(uniformName, data, data.length);
  28018. this.update();
  28019. };
  28020. /**
  28021. * Binds this uniform buffer to an effect.
  28022. * @param {Effect} effect
  28023. * @param {string} name Name of the uniform block in the shader.
  28024. */
  28025. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28026. this._currentEffect = effect;
  28027. if (this._noUBO || !this._buffer) {
  28028. return;
  28029. }
  28030. effect.bindUniformBuffer(this._buffer, name);
  28031. };
  28032. /**
  28033. * Disposes the uniform buffer.
  28034. */
  28035. UniformBuffer.prototype.dispose = function () {
  28036. if (this._noUBO) {
  28037. return;
  28038. }
  28039. var index = this._engine._uniformBuffers.indexOf(this);
  28040. if (index !== -1) {
  28041. this._engine._uniformBuffers.splice(index, 1);
  28042. }
  28043. if (!this._buffer) {
  28044. return;
  28045. }
  28046. if (this._engine._releaseBuffer(this._buffer)) {
  28047. this._buffer = null;
  28048. }
  28049. };
  28050. // Pool for avoiding memory leaks
  28051. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28052. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28053. return UniformBuffer;
  28054. }());
  28055. BABYLON.UniformBuffer = UniformBuffer;
  28056. })(BABYLON || (BABYLON = {}));
  28057. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28058. var BABYLON;
  28059. (function (BABYLON) {
  28060. var PushMaterial = /** @class */ (function (_super) {
  28061. __extends(PushMaterial, _super);
  28062. function PushMaterial(name, scene) {
  28063. var _this = _super.call(this, name, scene) || this;
  28064. _this.storeEffectOnSubMeshes = true;
  28065. return _this;
  28066. }
  28067. PushMaterial.prototype.getEffect = function () {
  28068. return this._activeEffect;
  28069. };
  28070. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  28071. if (!mesh) {
  28072. return false;
  28073. }
  28074. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  28075. return true;
  28076. }
  28077. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  28078. };
  28079. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  28080. this._activeEffect.setMatrix("world", world);
  28081. };
  28082. PushMaterial.prototype.bind = function (world, mesh) {
  28083. if (!mesh) {
  28084. return;
  28085. }
  28086. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  28087. };
  28088. PushMaterial.prototype._afterBind = function (mesh, effect) {
  28089. if (effect === void 0) { effect = null; }
  28090. _super.prototype._afterBind.call(this, mesh);
  28091. this.getScene()._cachedEffect = effect;
  28092. };
  28093. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  28094. if (visibility === void 0) { visibility = 1; }
  28095. return scene.isCachedMaterialInvalid(this, effect, visibility);
  28096. };
  28097. return PushMaterial;
  28098. }(BABYLON.Material));
  28099. BABYLON.PushMaterial = PushMaterial;
  28100. })(BABYLON || (BABYLON = {}));
  28101. //# sourceMappingURL=babylon.pushMaterial.js.map
  28102. var BABYLON;
  28103. (function (BABYLON) {
  28104. var VertexData = /** @class */ (function () {
  28105. function VertexData() {
  28106. }
  28107. VertexData.prototype.set = function (data, kind) {
  28108. switch (kind) {
  28109. case BABYLON.VertexBuffer.PositionKind:
  28110. this.positions = data;
  28111. break;
  28112. case BABYLON.VertexBuffer.NormalKind:
  28113. this.normals = data;
  28114. break;
  28115. case BABYLON.VertexBuffer.TangentKind:
  28116. this.tangents = data;
  28117. break;
  28118. case BABYLON.VertexBuffer.UVKind:
  28119. this.uvs = data;
  28120. break;
  28121. case BABYLON.VertexBuffer.UV2Kind:
  28122. this.uvs2 = data;
  28123. break;
  28124. case BABYLON.VertexBuffer.UV3Kind:
  28125. this.uvs3 = data;
  28126. break;
  28127. case BABYLON.VertexBuffer.UV4Kind:
  28128. this.uvs4 = data;
  28129. break;
  28130. case BABYLON.VertexBuffer.UV5Kind:
  28131. this.uvs5 = data;
  28132. break;
  28133. case BABYLON.VertexBuffer.UV6Kind:
  28134. this.uvs6 = data;
  28135. break;
  28136. case BABYLON.VertexBuffer.ColorKind:
  28137. this.colors = data;
  28138. break;
  28139. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28140. this.matricesIndices = data;
  28141. break;
  28142. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28143. this.matricesWeights = data;
  28144. break;
  28145. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28146. this.matricesIndicesExtra = data;
  28147. break;
  28148. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28149. this.matricesWeightsExtra = data;
  28150. break;
  28151. }
  28152. };
  28153. /**
  28154. * Associates the vertexData to the passed Mesh.
  28155. * Sets it as updatable or not (default `false`).
  28156. * Returns the VertexData.
  28157. */
  28158. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28159. this._applyTo(mesh, updatable);
  28160. return this;
  28161. };
  28162. /**
  28163. * Associates the vertexData to the passed Geometry.
  28164. * Sets it as updatable or not (default `false`).
  28165. * Returns the VertexData.
  28166. */
  28167. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28168. this._applyTo(geometry, updatable);
  28169. return this;
  28170. };
  28171. /**
  28172. * Updates the associated mesh.
  28173. * Returns the VertexData.
  28174. */
  28175. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28176. this._update(mesh);
  28177. return this;
  28178. };
  28179. /**
  28180. * Updates the associated geometry.
  28181. * Returns the VertexData.
  28182. */
  28183. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28184. this._update(geometry);
  28185. return this;
  28186. };
  28187. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  28188. if (updatable === void 0) { updatable = false; }
  28189. if (this.positions) {
  28190. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  28191. }
  28192. if (this.normals) {
  28193. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  28194. }
  28195. if (this.tangents) {
  28196. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  28197. }
  28198. if (this.uvs) {
  28199. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  28200. }
  28201. if (this.uvs2) {
  28202. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  28203. }
  28204. if (this.uvs3) {
  28205. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  28206. }
  28207. if (this.uvs4) {
  28208. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  28209. }
  28210. if (this.uvs5) {
  28211. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  28212. }
  28213. if (this.uvs6) {
  28214. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  28215. }
  28216. if (this.colors) {
  28217. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  28218. }
  28219. if (this.matricesIndices) {
  28220. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  28221. }
  28222. if (this.matricesWeights) {
  28223. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  28224. }
  28225. if (this.matricesIndicesExtra) {
  28226. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  28227. }
  28228. if (this.matricesWeightsExtra) {
  28229. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  28230. }
  28231. if (this.indices) {
  28232. meshOrGeometry.setIndices(this.indices, null, updatable);
  28233. }
  28234. return this;
  28235. };
  28236. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  28237. if (this.positions) {
  28238. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  28239. }
  28240. if (this.normals) {
  28241. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  28242. }
  28243. if (this.tangents) {
  28244. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  28245. }
  28246. if (this.uvs) {
  28247. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  28248. }
  28249. if (this.uvs2) {
  28250. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  28251. }
  28252. if (this.uvs3) {
  28253. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  28254. }
  28255. if (this.uvs4) {
  28256. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  28257. }
  28258. if (this.uvs5) {
  28259. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  28260. }
  28261. if (this.uvs6) {
  28262. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  28263. }
  28264. if (this.colors) {
  28265. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  28266. }
  28267. if (this.matricesIndices) {
  28268. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  28269. }
  28270. if (this.matricesWeights) {
  28271. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  28272. }
  28273. if (this.matricesIndicesExtra) {
  28274. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  28275. }
  28276. if (this.matricesWeightsExtra) {
  28277. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  28278. }
  28279. if (this.indices) {
  28280. meshOrGeometry.setIndices(this.indices, null);
  28281. }
  28282. return this;
  28283. };
  28284. /**
  28285. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  28286. * Returns the VertexData.
  28287. */
  28288. VertexData.prototype.transform = function (matrix) {
  28289. var transformed = BABYLON.Vector3.Zero();
  28290. var index;
  28291. if (this.positions) {
  28292. var position = BABYLON.Vector3.Zero();
  28293. for (index = 0; index < this.positions.length; index += 3) {
  28294. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  28295. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  28296. this.positions[index] = transformed.x;
  28297. this.positions[index + 1] = transformed.y;
  28298. this.positions[index + 2] = transformed.z;
  28299. }
  28300. }
  28301. if (this.normals) {
  28302. var normal = BABYLON.Vector3.Zero();
  28303. for (index = 0; index < this.normals.length; index += 3) {
  28304. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  28305. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  28306. this.normals[index] = transformed.x;
  28307. this.normals[index + 1] = transformed.y;
  28308. this.normals[index + 2] = transformed.z;
  28309. }
  28310. }
  28311. if (this.tangents) {
  28312. var tangent = BABYLON.Vector4.Zero();
  28313. var tangentTransformed = BABYLON.Vector4.Zero();
  28314. for (index = 0; index < this.tangents.length; index += 4) {
  28315. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  28316. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  28317. this.tangents[index] = tangentTransformed.x;
  28318. this.tangents[index + 1] = tangentTransformed.y;
  28319. this.tangents[index + 2] = tangentTransformed.z;
  28320. this.tangents[index + 3] = tangentTransformed.w;
  28321. }
  28322. }
  28323. return this;
  28324. };
  28325. /**
  28326. * Merges the passed VertexData into the current one.
  28327. * Returns the modified VertexData.
  28328. */
  28329. VertexData.prototype.merge = function (other, options) {
  28330. options = options || {};
  28331. if (other.indices) {
  28332. if (!this.indices) {
  28333. this.indices = [];
  28334. }
  28335. var offset = this.positions ? this.positions.length / 3 : 0;
  28336. for (var index = 0; index < other.indices.length; index++) {
  28337. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  28338. this.indices.push(other.indices[index] + offset);
  28339. }
  28340. }
  28341. this.positions = this._mergeElement(this.positions, other.positions);
  28342. if (!this.positions) {
  28343. return this;
  28344. }
  28345. var count = this.positions.length / 3;
  28346. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  28347. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  28348. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  28349. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  28350. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  28351. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  28352. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  28353. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  28354. this.colors = this._mergeElement(this.colors, other.colors, count * 4);
  28355. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  28356. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  28357. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  28358. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  28359. return this;
  28360. };
  28361. VertexData.prototype._mergeElement = function (source, other, length) {
  28362. if (length === void 0) { length = 0; }
  28363. if (!other && !source) {
  28364. return null;
  28365. }
  28366. if (!other) {
  28367. return this._mergeElement(source, new Float32Array(source.length), length);
  28368. }
  28369. if (!source) {
  28370. if (length === 0 || length === other.length) {
  28371. return other;
  28372. }
  28373. return this._mergeElement(new Float32Array(length - other.length), other, length);
  28374. }
  28375. var len = other.length + source.length;
  28376. var isSrcTypedArray = source instanceof Float32Array;
  28377. var isOthTypedArray = other instanceof Float32Array;
  28378. // use non-loop method when the source is Float32Array
  28379. if (isSrcTypedArray) {
  28380. var ret32 = new Float32Array(len);
  28381. ret32.set(source);
  28382. ret32.set(other, source.length);
  28383. return ret32;
  28384. // source is number[], when other is also use concat
  28385. }
  28386. else if (!isOthTypedArray) {
  28387. return source.concat(other);
  28388. // source is a number[], but other is a Float32Array, loop required
  28389. }
  28390. else {
  28391. var ret = source.slice(0); // copy source to a separate array
  28392. for (var i = 0, len = other.length; i < len; i++) {
  28393. ret.push(other[i]);
  28394. }
  28395. return ret;
  28396. }
  28397. };
  28398. /**
  28399. * Serializes the VertexData.
  28400. * Returns a serialized object.
  28401. */
  28402. VertexData.prototype.serialize = function () {
  28403. var serializationObject = this.serialize();
  28404. if (this.positions) {
  28405. serializationObject.positions = this.positions;
  28406. }
  28407. if (this.normals) {
  28408. serializationObject.normals = this.normals;
  28409. }
  28410. if (this.tangents) {
  28411. serializationObject.tangents = this.tangents;
  28412. }
  28413. if (this.uvs) {
  28414. serializationObject.uvs = this.uvs;
  28415. }
  28416. if (this.uvs2) {
  28417. serializationObject.uvs2 = this.uvs2;
  28418. }
  28419. if (this.uvs3) {
  28420. serializationObject.uvs3 = this.uvs3;
  28421. }
  28422. if (this.uvs4) {
  28423. serializationObject.uvs4 = this.uvs4;
  28424. }
  28425. if (this.uvs5) {
  28426. serializationObject.uvs5 = this.uvs5;
  28427. }
  28428. if (this.uvs6) {
  28429. serializationObject.uvs6 = this.uvs6;
  28430. }
  28431. if (this.colors) {
  28432. serializationObject.colors = this.colors;
  28433. }
  28434. if (this.matricesIndices) {
  28435. serializationObject.matricesIndices = this.matricesIndices;
  28436. serializationObject.matricesIndices._isExpanded = true;
  28437. }
  28438. if (this.matricesWeights) {
  28439. serializationObject.matricesWeights = this.matricesWeights;
  28440. }
  28441. if (this.matricesIndicesExtra) {
  28442. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  28443. serializationObject.matricesIndicesExtra._isExpanded = true;
  28444. }
  28445. if (this.matricesWeightsExtra) {
  28446. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  28447. }
  28448. serializationObject.indices = this.indices;
  28449. return serializationObject;
  28450. };
  28451. // Statics
  28452. /**
  28453. * Returns the object VertexData associated to the passed mesh.
  28454. */
  28455. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  28456. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  28457. };
  28458. /**
  28459. * Returns the object VertexData associated to the passed geometry.
  28460. */
  28461. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  28462. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  28463. };
  28464. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  28465. var result = new VertexData();
  28466. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28467. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  28468. }
  28469. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28470. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  28471. }
  28472. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28473. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  28474. }
  28475. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28476. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  28477. }
  28478. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28479. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  28480. }
  28481. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28482. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  28483. }
  28484. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28485. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  28486. }
  28487. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28488. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  28489. }
  28490. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28491. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  28492. }
  28493. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28494. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  28495. }
  28496. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  28497. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  28498. }
  28499. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  28500. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  28501. }
  28502. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  28503. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  28504. }
  28505. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  28506. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  28507. }
  28508. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  28509. return result;
  28510. };
  28511. /**
  28512. * Creates the vertexData of the Ribbon.
  28513. */
  28514. VertexData.CreateRibbon = function (options) {
  28515. var pathArray = options.pathArray;
  28516. var closeArray = options.closeArray || false;
  28517. var closePath = options.closePath || false;
  28518. var invertUV = options.invertUV || false;
  28519. var defaultOffset = Math.floor(pathArray[0].length / 2);
  28520. var offset = options.offset || defaultOffset;
  28521. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  28522. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28523. var customUV = options.uvs;
  28524. var customColors = options.colors;
  28525. var positions = [];
  28526. var indices = [];
  28527. var normals = [];
  28528. var uvs = [];
  28529. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  28530. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  28531. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  28532. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  28533. var minlg; // minimal length among all paths from pathArray
  28534. var lg = []; // array of path lengths : nb of vertex per path
  28535. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  28536. var p; // path iterator
  28537. var i; // point iterator
  28538. var j; // point iterator
  28539. // if single path in pathArray
  28540. if (pathArray.length < 2) {
  28541. var ar1 = [];
  28542. var ar2 = [];
  28543. for (i = 0; i < pathArray[0].length - offset; i++) {
  28544. ar1.push(pathArray[0][i]);
  28545. ar2.push(pathArray[0][i + offset]);
  28546. }
  28547. pathArray = [ar1, ar2];
  28548. }
  28549. // positions and horizontal distances (u)
  28550. var idc = 0;
  28551. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  28552. var path;
  28553. var l;
  28554. minlg = pathArray[0].length;
  28555. var vectlg;
  28556. var dist;
  28557. for (p = 0; p < pathArray.length; p++) {
  28558. uTotalDistance[p] = 0;
  28559. us[p] = [0];
  28560. path = pathArray[p];
  28561. l = path.length;
  28562. minlg = (minlg < l) ? minlg : l;
  28563. j = 0;
  28564. while (j < l) {
  28565. positions.push(path[j].x, path[j].y, path[j].z);
  28566. if (j > 0) {
  28567. vectlg = path[j].subtract(path[j - 1]).length();
  28568. dist = vectlg + uTotalDistance[p];
  28569. us[p].push(dist);
  28570. uTotalDistance[p] = dist;
  28571. }
  28572. j++;
  28573. }
  28574. if (closePath) {
  28575. j--;
  28576. positions.push(path[0].x, path[0].y, path[0].z);
  28577. vectlg = path[j].subtract(path[0]).length();
  28578. dist = vectlg + uTotalDistance[p];
  28579. us[p].push(dist);
  28580. uTotalDistance[p] = dist;
  28581. }
  28582. lg[p] = l + closePathCorr;
  28583. idx[p] = idc;
  28584. idc += (l + closePathCorr);
  28585. }
  28586. // vertical distances (v)
  28587. var path1;
  28588. var path2;
  28589. var vertex1 = null;
  28590. var vertex2 = null;
  28591. for (i = 0; i < minlg + closePathCorr; i++) {
  28592. vTotalDistance[i] = 0;
  28593. vs[i] = [0];
  28594. for (p = 0; p < pathArray.length - 1; p++) {
  28595. path1 = pathArray[p];
  28596. path2 = pathArray[p + 1];
  28597. if (i === minlg) {
  28598. vertex1 = path1[0];
  28599. vertex2 = path2[0];
  28600. }
  28601. else {
  28602. vertex1 = path1[i];
  28603. vertex2 = path2[i];
  28604. }
  28605. vectlg = vertex2.subtract(vertex1).length();
  28606. dist = vectlg + vTotalDistance[i];
  28607. vs[i].push(dist);
  28608. vTotalDistance[i] = dist;
  28609. }
  28610. if (closeArray && vertex2 && vertex1) {
  28611. path1 = pathArray[p];
  28612. path2 = pathArray[0];
  28613. if (i === minlg) {
  28614. vertex2 = path2[0];
  28615. }
  28616. vectlg = vertex2.subtract(vertex1).length();
  28617. dist = vectlg + vTotalDistance[i];
  28618. vTotalDistance[i] = dist;
  28619. }
  28620. }
  28621. // uvs
  28622. var u;
  28623. var v;
  28624. if (customUV) {
  28625. for (p = 0; p < customUV.length; p++) {
  28626. uvs.push(customUV[p].x, customUV[p].y);
  28627. }
  28628. }
  28629. else {
  28630. for (p = 0; p < pathArray.length; p++) {
  28631. for (i = 0; i < minlg + closePathCorr; i++) {
  28632. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  28633. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  28634. if (invertUV) {
  28635. uvs.push(v, u);
  28636. }
  28637. else {
  28638. uvs.push(u, v);
  28639. }
  28640. }
  28641. }
  28642. }
  28643. // indices
  28644. p = 0; // path index
  28645. var pi = 0; // positions array index
  28646. var l1 = lg[p] - 1; // path1 length
  28647. var l2 = lg[p + 1] - 1; // path2 length
  28648. var min = (l1 < l2) ? l1 : l2; // current path stop index
  28649. var shft = idx[1] - idx[0]; // shift
  28650. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  28651. while (pi <= min && p < path1nb) {
  28652. // 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
  28653. indices.push(pi, pi + shft, pi + 1);
  28654. indices.push(pi + shft + 1, pi + 1, pi + shft);
  28655. pi += 1;
  28656. if (pi === min) {
  28657. p++;
  28658. if (p === lg.length - 1) {
  28659. shft = idx[0] - idx[p];
  28660. l1 = lg[p] - 1;
  28661. l2 = lg[0] - 1;
  28662. }
  28663. else {
  28664. shft = idx[p + 1] - idx[p];
  28665. l1 = lg[p] - 1;
  28666. l2 = lg[p + 1] - 1;
  28667. }
  28668. pi = idx[p];
  28669. min = (l1 < l2) ? l1 + pi : l2 + pi;
  28670. }
  28671. }
  28672. // normals
  28673. VertexData.ComputeNormals(positions, indices, normals);
  28674. if (closePath) {
  28675. var indexFirst = 0;
  28676. var indexLast = 0;
  28677. for (p = 0; p < pathArray.length; p++) {
  28678. indexFirst = idx[p] * 3;
  28679. if (p + 1 < pathArray.length) {
  28680. indexLast = (idx[p + 1] - 1) * 3;
  28681. }
  28682. else {
  28683. indexLast = normals.length - 3;
  28684. }
  28685. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  28686. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  28687. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  28688. normals[indexLast] = normals[indexFirst];
  28689. normals[indexLast + 1] = normals[indexFirst + 1];
  28690. normals[indexLast + 2] = normals[indexFirst + 2];
  28691. }
  28692. }
  28693. // sides
  28694. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28695. // Colors
  28696. var colors = null;
  28697. if (customColors) {
  28698. colors = new Float32Array(customColors.length * 4);
  28699. for (var c = 0; c < customColors.length; c++) {
  28700. colors[c * 4] = customColors[c].r;
  28701. colors[c * 4 + 1] = customColors[c].g;
  28702. colors[c * 4 + 2] = customColors[c].b;
  28703. colors[c * 4 + 3] = customColors[c].a;
  28704. }
  28705. }
  28706. // Result
  28707. var vertexData = new VertexData();
  28708. var positions32 = new Float32Array(positions);
  28709. var normals32 = new Float32Array(normals);
  28710. var uvs32 = new Float32Array(uvs);
  28711. vertexData.indices = indices;
  28712. vertexData.positions = positions32;
  28713. vertexData.normals = normals32;
  28714. vertexData.uvs = uvs32;
  28715. if (colors) {
  28716. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  28717. }
  28718. if (closePath) {
  28719. vertexData._idx = idx;
  28720. }
  28721. return vertexData;
  28722. };
  28723. /**
  28724. * Creates the VertexData of the Box.
  28725. */
  28726. VertexData.CreateBox = function (options) {
  28727. var normalsSource = [
  28728. new BABYLON.Vector3(0, 0, 1),
  28729. new BABYLON.Vector3(0, 0, -1),
  28730. new BABYLON.Vector3(1, 0, 0),
  28731. new BABYLON.Vector3(-1, 0, 0),
  28732. new BABYLON.Vector3(0, 1, 0),
  28733. new BABYLON.Vector3(0, -1, 0)
  28734. ];
  28735. var indices = [];
  28736. var positions = [];
  28737. var normals = [];
  28738. var uvs = [];
  28739. var width = options.width || options.size || 1;
  28740. var height = options.height || options.size || 1;
  28741. var depth = options.depth || options.size || 1;
  28742. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28743. var faceUV = options.faceUV || new Array(6);
  28744. var faceColors = options.faceColors;
  28745. var colors = [];
  28746. // default face colors and UV if undefined
  28747. for (var f = 0; f < 6; f++) {
  28748. if (faceUV[f] === undefined) {
  28749. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28750. }
  28751. if (faceColors && faceColors[f] === undefined) {
  28752. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28753. }
  28754. }
  28755. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  28756. // Create each face in turn.
  28757. for (var index = 0; index < normalsSource.length; index++) {
  28758. var normal = normalsSource[index];
  28759. // Get two vectors perpendicular to the face normal and to each other.
  28760. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  28761. var side2 = BABYLON.Vector3.Cross(normal, side1);
  28762. // Six indices (two triangles) per face.
  28763. var verticesLength = positions.length / 3;
  28764. indices.push(verticesLength);
  28765. indices.push(verticesLength + 1);
  28766. indices.push(verticesLength + 2);
  28767. indices.push(verticesLength);
  28768. indices.push(verticesLength + 2);
  28769. indices.push(verticesLength + 3);
  28770. // Four vertices per face.
  28771. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  28772. positions.push(vertex.x, vertex.y, vertex.z);
  28773. normals.push(normal.x, normal.y, normal.z);
  28774. uvs.push(faceUV[index].z, faceUV[index].w);
  28775. if (faceColors) {
  28776. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28777. }
  28778. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  28779. positions.push(vertex.x, vertex.y, vertex.z);
  28780. normals.push(normal.x, normal.y, normal.z);
  28781. uvs.push(faceUV[index].x, faceUV[index].w);
  28782. if (faceColors) {
  28783. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28784. }
  28785. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  28786. positions.push(vertex.x, vertex.y, vertex.z);
  28787. normals.push(normal.x, normal.y, normal.z);
  28788. uvs.push(faceUV[index].x, faceUV[index].y);
  28789. if (faceColors) {
  28790. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28791. }
  28792. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  28793. positions.push(vertex.x, vertex.y, vertex.z);
  28794. normals.push(normal.x, normal.y, normal.z);
  28795. uvs.push(faceUV[index].z, faceUV[index].y);
  28796. if (faceColors) {
  28797. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  28798. }
  28799. }
  28800. // sides
  28801. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28802. // Result
  28803. var vertexData = new VertexData();
  28804. vertexData.indices = indices;
  28805. vertexData.positions = positions;
  28806. vertexData.normals = normals;
  28807. vertexData.uvs = uvs;
  28808. if (faceColors) {
  28809. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  28810. vertexData.colors = totalColors;
  28811. }
  28812. return vertexData;
  28813. };
  28814. /**
  28815. * Creates the VertexData of the Sphere.
  28816. */
  28817. VertexData.CreateSphere = function (options) {
  28818. var segments = options.segments || 32;
  28819. var diameterX = options.diameterX || options.diameter || 1;
  28820. var diameterY = options.diameterY || options.diameter || 1;
  28821. var diameterZ = options.diameterZ || options.diameter || 1;
  28822. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28823. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  28824. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28825. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  28826. var totalZRotationSteps = 2 + segments;
  28827. var totalYRotationSteps = 2 * totalZRotationSteps;
  28828. var indices = [];
  28829. var positions = [];
  28830. var normals = [];
  28831. var uvs = [];
  28832. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  28833. var normalizedZ = zRotationStep / totalZRotationSteps;
  28834. var angleZ = normalizedZ * Math.PI * slice;
  28835. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  28836. var normalizedY = yRotationStep / totalYRotationSteps;
  28837. var angleY = normalizedY * Math.PI * 2 * arc;
  28838. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  28839. var rotationY = BABYLON.Matrix.RotationY(angleY);
  28840. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  28841. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  28842. var vertex = complete.multiply(radius);
  28843. var normal = complete.divide(radius).normalize();
  28844. positions.push(vertex.x, vertex.y, vertex.z);
  28845. normals.push(normal.x, normal.y, normal.z);
  28846. uvs.push(normalizedY, normalizedZ);
  28847. }
  28848. if (zRotationStep > 0) {
  28849. var verticesCount = positions.length / 3;
  28850. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  28851. indices.push((firstIndex));
  28852. indices.push((firstIndex + 1));
  28853. indices.push(firstIndex + totalYRotationSteps + 1);
  28854. indices.push((firstIndex + totalYRotationSteps + 1));
  28855. indices.push((firstIndex + 1));
  28856. indices.push((firstIndex + totalYRotationSteps + 2));
  28857. }
  28858. }
  28859. }
  28860. // Sides
  28861. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28862. // Result
  28863. var vertexData = new VertexData();
  28864. vertexData.indices = indices;
  28865. vertexData.positions = positions;
  28866. vertexData.normals = normals;
  28867. vertexData.uvs = uvs;
  28868. return vertexData;
  28869. };
  28870. /**
  28871. * Creates the VertexData of the Cylinder or Cone.
  28872. */
  28873. VertexData.CreateCylinder = function (options) {
  28874. var height = options.height || 2;
  28875. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  28876. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  28877. var tessellation = options.tessellation || 24;
  28878. var subdivisions = options.subdivisions || 1;
  28879. var hasRings = options.hasRings ? true : false;
  28880. var enclose = options.enclose ? true : false;
  28881. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  28882. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28883. var faceUV = options.faceUV || new Array(3);
  28884. var faceColors = options.faceColors;
  28885. // default face colors and UV if undefined
  28886. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  28887. var ringNb = (hasRings) ? subdivisions : 1;
  28888. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  28889. var f;
  28890. for (f = 0; f < surfaceNb; f++) {
  28891. if (faceColors && faceColors[f] === undefined) {
  28892. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  28893. }
  28894. }
  28895. for (f = 0; f < surfaceNb; f++) {
  28896. if (faceUV && faceUV[f] === undefined) {
  28897. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  28898. }
  28899. }
  28900. var indices = new Array();
  28901. var positions = new Array();
  28902. var normals = new Array();
  28903. var uvs = new Array();
  28904. var colors = new Array();
  28905. var angle_step = Math.PI * 2 * arc / tessellation;
  28906. var angle;
  28907. var h;
  28908. var radius;
  28909. var tan = (diameterBottom - diameterTop) / 2 / height;
  28910. var ringVertex = BABYLON.Vector3.Zero();
  28911. var ringNormal = BABYLON.Vector3.Zero();
  28912. var ringFirstVertex = BABYLON.Vector3.Zero();
  28913. var ringFirstNormal = BABYLON.Vector3.Zero();
  28914. var quadNormal = BABYLON.Vector3.Zero();
  28915. var Y = BABYLON.Axis.Y;
  28916. // positions, normals, uvs
  28917. var i;
  28918. var j;
  28919. var r;
  28920. var ringIdx = 1;
  28921. var s = 1; // surface index
  28922. var cs = 0;
  28923. var v = 0;
  28924. for (i = 0; i <= subdivisions; i++) {
  28925. h = i / subdivisions;
  28926. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  28927. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  28928. for (r = 0; r < ringIdx; r++) {
  28929. if (hasRings) {
  28930. s += r;
  28931. }
  28932. if (enclose) {
  28933. s += 2 * r;
  28934. }
  28935. for (j = 0; j <= tessellation; j++) {
  28936. angle = j * angle_step;
  28937. // position
  28938. ringVertex.x = Math.cos(-angle) * radius;
  28939. ringVertex.y = -height / 2 + h * height;
  28940. ringVertex.z = Math.sin(-angle) * radius;
  28941. // normal
  28942. if (diameterTop === 0 && i === subdivisions) {
  28943. // if no top cap, reuse former normals
  28944. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  28945. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  28946. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  28947. }
  28948. else {
  28949. ringNormal.x = ringVertex.x;
  28950. ringNormal.z = ringVertex.z;
  28951. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  28952. ringNormal.normalize();
  28953. }
  28954. // keep first ring vertex values for enclose
  28955. if (j === 0) {
  28956. ringFirstVertex.copyFrom(ringVertex);
  28957. ringFirstNormal.copyFrom(ringNormal);
  28958. }
  28959. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28960. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  28961. if (hasRings) {
  28962. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  28963. }
  28964. else {
  28965. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  28966. }
  28967. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  28968. if (faceColors) {
  28969. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  28970. }
  28971. }
  28972. // if enclose, add four vertices and their dedicated normals
  28973. if (arc !== 1 && enclose) {
  28974. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  28975. positions.push(0, ringVertex.y, 0);
  28976. positions.push(0, ringVertex.y, 0);
  28977. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  28978. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  28979. quadNormal.normalize();
  28980. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28981. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  28982. quadNormal.normalize();
  28983. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  28984. if (hasRings) {
  28985. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  28986. }
  28987. else {
  28988. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  28989. }
  28990. uvs.push(faceUV[s + 1].x, v);
  28991. uvs.push(faceUV[s + 1].z, v);
  28992. if (hasRings) {
  28993. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  28994. }
  28995. else {
  28996. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  28997. }
  28998. uvs.push(faceUV[s + 2].x, v);
  28999. uvs.push(faceUV[s + 2].z, v);
  29000. if (faceColors) {
  29001. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29002. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29003. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29004. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29005. }
  29006. }
  29007. if (cs !== s) {
  29008. cs = s;
  29009. }
  29010. }
  29011. }
  29012. // indices
  29013. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29014. var s;
  29015. i = 0;
  29016. for (s = 0; s < subdivisions; s++) {
  29017. var i0 = 0;
  29018. var i1 = 0;
  29019. var i2 = 0;
  29020. var i3 = 0;
  29021. for (j = 0; j < tessellation; j++) {
  29022. i0 = i * (e + 1) + j;
  29023. i1 = (i + 1) * (e + 1) + j;
  29024. i2 = i * (e + 1) + (j + 1);
  29025. i3 = (i + 1) * (e + 1) + (j + 1);
  29026. indices.push(i0, i1, i2);
  29027. indices.push(i3, i2, i1);
  29028. }
  29029. if (arc !== 1 && enclose) {
  29030. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29031. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29032. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29033. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29034. }
  29035. i = (hasRings) ? (i + 2) : (i + 1);
  29036. }
  29037. // Caps
  29038. var createCylinderCap = function (isTop) {
  29039. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29040. if (radius === 0) {
  29041. return;
  29042. }
  29043. // Cap positions, normals & uvs
  29044. var angle;
  29045. var circleVector;
  29046. var i;
  29047. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29048. var c = null;
  29049. if (faceColors) {
  29050. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29051. }
  29052. // cap center
  29053. var vbase = positions.length / 3;
  29054. var offset = isTop ? height / 2 : -height / 2;
  29055. var center = new BABYLON.Vector3(0, offset, 0);
  29056. positions.push(center.x, center.y, center.z);
  29057. normals.push(0, isTop ? 1 : -1, 0);
  29058. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29059. if (c) {
  29060. colors.push(c.r, c.g, c.b, c.a);
  29061. }
  29062. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29063. for (i = 0; i <= tessellation; i++) {
  29064. angle = Math.PI * 2 * i * arc / tessellation;
  29065. var cos = Math.cos(-angle);
  29066. var sin = Math.sin(-angle);
  29067. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29068. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29069. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29070. normals.push(0, isTop ? 1 : -1, 0);
  29071. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29072. if (c) {
  29073. colors.push(c.r, c.g, c.b, c.a);
  29074. }
  29075. }
  29076. // Cap indices
  29077. for (i = 0; i < tessellation; i++) {
  29078. if (!isTop) {
  29079. indices.push(vbase);
  29080. indices.push(vbase + (i + 1));
  29081. indices.push(vbase + (i + 2));
  29082. }
  29083. else {
  29084. indices.push(vbase);
  29085. indices.push(vbase + (i + 2));
  29086. indices.push(vbase + (i + 1));
  29087. }
  29088. }
  29089. };
  29090. // add caps to geometry
  29091. createCylinderCap(false);
  29092. createCylinderCap(true);
  29093. // Sides
  29094. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29095. var vertexData = new VertexData();
  29096. vertexData.indices = indices;
  29097. vertexData.positions = positions;
  29098. vertexData.normals = normals;
  29099. vertexData.uvs = uvs;
  29100. if (faceColors) {
  29101. vertexData.colors = colors;
  29102. }
  29103. return vertexData;
  29104. };
  29105. /**
  29106. * Creates the VertexData of the Torus.
  29107. */
  29108. VertexData.CreateTorus = function (options) {
  29109. var indices = [];
  29110. var positions = [];
  29111. var normals = [];
  29112. var uvs = [];
  29113. var diameter = options.diameter || 1;
  29114. var thickness = options.thickness || 0.5;
  29115. var tessellation = options.tessellation || 16;
  29116. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29117. var stride = tessellation + 1;
  29118. for (var i = 0; i <= tessellation; i++) {
  29119. var u = i / tessellation;
  29120. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29121. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29122. for (var j = 0; j <= tessellation; j++) {
  29123. var v = 1 - j / tessellation;
  29124. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29125. var dx = Math.cos(innerAngle);
  29126. var dy = Math.sin(innerAngle);
  29127. // Create a vertex.
  29128. var normal = new BABYLON.Vector3(dx, dy, 0);
  29129. var position = normal.scale(thickness / 2);
  29130. var textureCoordinate = new BABYLON.Vector2(u, v);
  29131. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29132. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29133. positions.push(position.x, position.y, position.z);
  29134. normals.push(normal.x, normal.y, normal.z);
  29135. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29136. // And create indices for two triangles.
  29137. var nextI = (i + 1) % stride;
  29138. var nextJ = (j + 1) % stride;
  29139. indices.push(i * stride + j);
  29140. indices.push(i * stride + nextJ);
  29141. indices.push(nextI * stride + j);
  29142. indices.push(i * stride + nextJ);
  29143. indices.push(nextI * stride + nextJ);
  29144. indices.push(nextI * stride + j);
  29145. }
  29146. }
  29147. // Sides
  29148. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29149. // Result
  29150. var vertexData = new VertexData();
  29151. vertexData.indices = indices;
  29152. vertexData.positions = positions;
  29153. vertexData.normals = normals;
  29154. vertexData.uvs = uvs;
  29155. return vertexData;
  29156. };
  29157. /**
  29158. * Creates the VertexData of the LineSystem.
  29159. */
  29160. VertexData.CreateLineSystem = function (options) {
  29161. var indices = [];
  29162. var positions = [];
  29163. var lines = options.lines;
  29164. var idx = 0;
  29165. for (var l = 0; l < lines.length; l++) {
  29166. var points = lines[l];
  29167. for (var index = 0; index < points.length; index++) {
  29168. positions.push(points[index].x, points[index].y, points[index].z);
  29169. if (index > 0) {
  29170. indices.push(idx - 1);
  29171. indices.push(idx);
  29172. }
  29173. idx++;
  29174. }
  29175. }
  29176. var vertexData = new VertexData();
  29177. vertexData.indices = indices;
  29178. vertexData.positions = positions;
  29179. return vertexData;
  29180. };
  29181. /**
  29182. * Create the VertexData of the DashedLines.
  29183. */
  29184. VertexData.CreateDashedLines = function (options) {
  29185. var dashSize = options.dashSize || 3;
  29186. var gapSize = options.gapSize || 1;
  29187. var dashNb = options.dashNb || 200;
  29188. var points = options.points;
  29189. var positions = new Array();
  29190. var indices = new Array();
  29191. var curvect = BABYLON.Vector3.Zero();
  29192. var lg = 0;
  29193. var nb = 0;
  29194. var shft = 0;
  29195. var dashshft = 0;
  29196. var curshft = 0;
  29197. var idx = 0;
  29198. var i = 0;
  29199. for (i = 0; i < points.length - 1; i++) {
  29200. points[i + 1].subtractToRef(points[i], curvect);
  29201. lg += curvect.length();
  29202. }
  29203. shft = lg / dashNb;
  29204. dashshft = dashSize * shft / (dashSize + gapSize);
  29205. for (i = 0; i < points.length - 1; i++) {
  29206. points[i + 1].subtractToRef(points[i], curvect);
  29207. nb = Math.floor(curvect.length() / shft);
  29208. curvect.normalize();
  29209. for (var j = 0; j < nb; j++) {
  29210. curshft = shft * j;
  29211. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  29212. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  29213. indices.push(idx, idx + 1);
  29214. idx += 2;
  29215. }
  29216. }
  29217. // Result
  29218. var vertexData = new VertexData();
  29219. vertexData.positions = positions;
  29220. vertexData.indices = indices;
  29221. return vertexData;
  29222. };
  29223. /**
  29224. * Creates the VertexData of the Ground.
  29225. */
  29226. VertexData.CreateGround = function (options) {
  29227. var indices = [];
  29228. var positions = [];
  29229. var normals = [];
  29230. var uvs = [];
  29231. var row, col;
  29232. var width = options.width || 1;
  29233. var height = options.height || 1;
  29234. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  29235. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  29236. for (row = 0; row <= subdivisionsY; row++) {
  29237. for (col = 0; col <= subdivisionsX; col++) {
  29238. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  29239. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29240. positions.push(position.x, position.y, position.z);
  29241. normals.push(normal.x, normal.y, normal.z);
  29242. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  29243. }
  29244. }
  29245. for (row = 0; row < subdivisionsY; row++) {
  29246. for (col = 0; col < subdivisionsX; col++) {
  29247. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29248. indices.push(col + 1 + row * (subdivisionsX + 1));
  29249. indices.push(col + row * (subdivisionsX + 1));
  29250. indices.push(col + (row + 1) * (subdivisionsX + 1));
  29251. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  29252. indices.push(col + row * (subdivisionsX + 1));
  29253. }
  29254. }
  29255. // Result
  29256. var vertexData = new VertexData();
  29257. vertexData.indices = indices;
  29258. vertexData.positions = positions;
  29259. vertexData.normals = normals;
  29260. vertexData.uvs = uvs;
  29261. return vertexData;
  29262. };
  29263. /**
  29264. * Creates the VertexData of the TiledGround.
  29265. */
  29266. VertexData.CreateTiledGround = function (options) {
  29267. var xmin = options.xmin || -1.0;
  29268. var zmin = options.zmin || -1.0;
  29269. var xmax = options.xmax || 1.0;
  29270. var zmax = options.zmax || 1.0;
  29271. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  29272. var precision = options.precision || { w: 1, h: 1 };
  29273. var indices = new Array();
  29274. var positions = new Array();
  29275. var normals = new Array();
  29276. var uvs = new Array();
  29277. var row, col, tileRow, tileCol;
  29278. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  29279. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  29280. precision.w = (precision.w < 1) ? 1 : precision.w;
  29281. precision.h = (precision.h < 1) ? 1 : precision.h;
  29282. var tileSize = {
  29283. 'w': (xmax - xmin) / subdivisions.w,
  29284. 'h': (zmax - zmin) / subdivisions.h
  29285. };
  29286. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  29287. // Indices
  29288. var base = positions.length / 3;
  29289. var rowLength = precision.w + 1;
  29290. for (row = 0; row < precision.h; row++) {
  29291. for (col = 0; col < precision.w; col++) {
  29292. var square = [
  29293. base + col + row * rowLength,
  29294. base + (col + 1) + row * rowLength,
  29295. base + (col + 1) + (row + 1) * rowLength,
  29296. base + col + (row + 1) * rowLength
  29297. ];
  29298. indices.push(square[1]);
  29299. indices.push(square[2]);
  29300. indices.push(square[3]);
  29301. indices.push(square[0]);
  29302. indices.push(square[1]);
  29303. indices.push(square[3]);
  29304. }
  29305. }
  29306. // Position, normals and uvs
  29307. var position = BABYLON.Vector3.Zero();
  29308. var normal = new BABYLON.Vector3(0, 1.0, 0);
  29309. for (row = 0; row <= precision.h; row++) {
  29310. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  29311. for (col = 0; col <= precision.w; col++) {
  29312. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  29313. position.y = 0;
  29314. positions.push(position.x, position.y, position.z);
  29315. normals.push(normal.x, normal.y, normal.z);
  29316. uvs.push(col / precision.w, row / precision.h);
  29317. }
  29318. }
  29319. }
  29320. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  29321. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  29322. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  29323. }
  29324. }
  29325. // Result
  29326. var vertexData = new VertexData();
  29327. vertexData.indices = indices;
  29328. vertexData.positions = positions;
  29329. vertexData.normals = normals;
  29330. vertexData.uvs = uvs;
  29331. return vertexData;
  29332. };
  29333. /**
  29334. * Creates the VertexData of the Ground designed from a heightmap.
  29335. */
  29336. VertexData.CreateGroundFromHeightMap = function (options) {
  29337. var indices = [];
  29338. var positions = [];
  29339. var normals = [];
  29340. var uvs = [];
  29341. var row, col;
  29342. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  29343. // Vertices
  29344. for (row = 0; row <= options.subdivisions; row++) {
  29345. for (col = 0; col <= options.subdivisions; col++) {
  29346. 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));
  29347. // Compute height
  29348. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  29349. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  29350. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  29351. var r = options.buffer[pos] / 255.0;
  29352. var g = options.buffer[pos + 1] / 255.0;
  29353. var b = options.buffer[pos + 2] / 255.0;
  29354. var gradient = r * filter.r + g * filter.g + b * filter.b;
  29355. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  29356. // Add vertex
  29357. positions.push(position.x, position.y, position.z);
  29358. normals.push(0, 0, 0);
  29359. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  29360. }
  29361. }
  29362. // Indices
  29363. for (row = 0; row < options.subdivisions; row++) {
  29364. for (col = 0; col < options.subdivisions; col++) {
  29365. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29366. indices.push(col + 1 + row * (options.subdivisions + 1));
  29367. indices.push(col + row * (options.subdivisions + 1));
  29368. indices.push(col + (row + 1) * (options.subdivisions + 1));
  29369. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  29370. indices.push(col + row * (options.subdivisions + 1));
  29371. }
  29372. }
  29373. // Normals
  29374. VertexData.ComputeNormals(positions, indices, normals);
  29375. // Result
  29376. var vertexData = new VertexData();
  29377. vertexData.indices = indices;
  29378. vertexData.positions = positions;
  29379. vertexData.normals = normals;
  29380. vertexData.uvs = uvs;
  29381. return vertexData;
  29382. };
  29383. /**
  29384. * Creates the VertexData of the Plane.
  29385. */
  29386. VertexData.CreatePlane = function (options) {
  29387. var indices = [];
  29388. var positions = [];
  29389. var normals = [];
  29390. var uvs = [];
  29391. var width = options.width || options.size || 1;
  29392. var height = options.height || options.size || 1;
  29393. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29394. // Vertices
  29395. var halfWidth = width / 2.0;
  29396. var halfHeight = height / 2.0;
  29397. positions.push(-halfWidth, -halfHeight, 0);
  29398. normals.push(0, 0, -1.0);
  29399. uvs.push(0.0, 0.0);
  29400. positions.push(halfWidth, -halfHeight, 0);
  29401. normals.push(0, 0, -1.0);
  29402. uvs.push(1.0, 0.0);
  29403. positions.push(halfWidth, halfHeight, 0);
  29404. normals.push(0, 0, -1.0);
  29405. uvs.push(1.0, 1.0);
  29406. positions.push(-halfWidth, halfHeight, 0);
  29407. normals.push(0, 0, -1.0);
  29408. uvs.push(0.0, 1.0);
  29409. // Indices
  29410. indices.push(0);
  29411. indices.push(1);
  29412. indices.push(2);
  29413. indices.push(0);
  29414. indices.push(2);
  29415. indices.push(3);
  29416. // Sides
  29417. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29418. // Result
  29419. var vertexData = new VertexData();
  29420. vertexData.indices = indices;
  29421. vertexData.positions = positions;
  29422. vertexData.normals = normals;
  29423. vertexData.uvs = uvs;
  29424. return vertexData;
  29425. };
  29426. /**
  29427. * Creates the VertexData of the Disc or regular Polygon.
  29428. */
  29429. VertexData.CreateDisc = function (options) {
  29430. var positions = new Array();
  29431. var indices = new Array();
  29432. var normals = new Array();
  29433. var uvs = new Array();
  29434. var radius = options.radius || 0.5;
  29435. var tessellation = options.tessellation || 64;
  29436. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29437. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29438. // positions and uvs
  29439. positions.push(0, 0, 0); // disc center first
  29440. uvs.push(0.5, 0.5);
  29441. var theta = Math.PI * 2 * arc;
  29442. var step = theta / tessellation;
  29443. for (var a = 0; a < theta; a += step) {
  29444. var x = Math.cos(a);
  29445. var y = Math.sin(a);
  29446. var u = (x + 1) / 2;
  29447. var v = (1 - y) / 2;
  29448. positions.push(radius * x, radius * y, 0);
  29449. uvs.push(u, v);
  29450. }
  29451. if (arc === 1) {
  29452. positions.push(positions[3], positions[4], positions[5]); // close the circle
  29453. uvs.push(uvs[2], uvs[3]);
  29454. }
  29455. //indices
  29456. var vertexNb = positions.length / 3;
  29457. for (var i = 1; i < vertexNb - 1; i++) {
  29458. indices.push(i + 1, 0, i);
  29459. }
  29460. // result
  29461. VertexData.ComputeNormals(positions, indices, normals);
  29462. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29463. var vertexData = new VertexData();
  29464. vertexData.indices = indices;
  29465. vertexData.positions = positions;
  29466. vertexData.normals = normals;
  29467. vertexData.uvs = uvs;
  29468. return vertexData;
  29469. };
  29470. /**
  29471. * Re-creates the VertexData of the Polygon for sideOrientation.
  29472. */
  29473. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  29474. var faceUV = fUV || new Array(3);
  29475. var faceColors = fColors;
  29476. var colors = [];
  29477. // default face colors and UV if undefined
  29478. for (var f = 0; f < 3; f++) {
  29479. if (faceUV[f] === undefined) {
  29480. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29481. }
  29482. if (faceColors && faceColors[f] === undefined) {
  29483. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29484. }
  29485. }
  29486. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29487. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29488. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29489. var indices = polygon.getIndices();
  29490. // set face colours and textures
  29491. var idx = 0;
  29492. var face = 0;
  29493. for (var index = 0; index < normals.length; index += 3) {
  29494. //Edge Face no. 1
  29495. if (Math.abs(normals[index + 1]) < 0.001) {
  29496. face = 1;
  29497. }
  29498. //Top Face no. 0
  29499. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  29500. face = 0;
  29501. }
  29502. //Bottom Face no. 2
  29503. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  29504. face = 2;
  29505. }
  29506. idx = index / 3;
  29507. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  29508. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  29509. if (faceColors) {
  29510. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  29511. }
  29512. }
  29513. // sides
  29514. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  29515. // Result
  29516. var vertexData = new VertexData();
  29517. vertexData.indices = indices;
  29518. vertexData.positions = positions;
  29519. vertexData.normals = normals;
  29520. vertexData.uvs = uvs;
  29521. if (faceColors) {
  29522. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29523. vertexData.colors = totalColors;
  29524. }
  29525. return vertexData;
  29526. };
  29527. /**
  29528. * Creates the VertexData of the IcoSphere.
  29529. */
  29530. VertexData.CreateIcoSphere = function (options) {
  29531. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29532. var radius = options.radius || 1;
  29533. var flat = (options.flat === undefined) ? true : options.flat;
  29534. var subdivisions = options.subdivisions || 4;
  29535. var radiusX = options.radiusX || radius;
  29536. var radiusY = options.radiusY || radius;
  29537. var radiusZ = options.radiusZ || radius;
  29538. var t = (1 + Math.sqrt(5)) / 2;
  29539. // 12 vertex x,y,z
  29540. var ico_vertices = [
  29541. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  29542. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  29543. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  29544. ];
  29545. // index of 3 vertex makes a face of icopshere
  29546. var ico_indices = [
  29547. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  29548. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  29549. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  29550. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  29551. ];
  29552. // vertex for uv have aliased position, not for UV
  29553. var vertices_unalias_id = [
  29554. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  29555. // vertex alias
  29556. 0,
  29557. 2,
  29558. 3,
  29559. 3,
  29560. 3,
  29561. 4,
  29562. 7,
  29563. 8,
  29564. 9,
  29565. 9,
  29566. 10,
  29567. 11 // 23: B + 12
  29568. ];
  29569. // uv as integer step (not pixels !)
  29570. var ico_vertexuv = [
  29571. 5, 1, 3, 1, 6, 4, 0, 0,
  29572. 5, 3, 4, 2, 2, 2, 4, 0,
  29573. 2, 0, 1, 1, 6, 0, 6, 2,
  29574. // vertex alias (for same vertex on different faces)
  29575. 0, 4,
  29576. 3, 3,
  29577. 4, 4,
  29578. 3, 1,
  29579. 4, 2,
  29580. 4, 4,
  29581. 0, 2,
  29582. 1, 1,
  29583. 2, 2,
  29584. 3, 3,
  29585. 1, 3,
  29586. 2, 4 // 23: B + 12
  29587. ];
  29588. // Vertices[0, 1, ...9, A, B] : position on UV plane
  29589. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  29590. // First island of uv mapping
  29591. // v = 4h 3+ 2
  29592. // v = 3h 9+ 4
  29593. // v = 2h 9+ 5 B
  29594. // v = 1h 9 1 0
  29595. // v = 0h 3 8 7 A
  29596. // u = 0 1 2 3 4 5 6 *a
  29597. // Second island of uv mapping
  29598. // v = 4h 0+ B+ 4+
  29599. // v = 3h A+ 2+
  29600. // v = 2h 7+ 6 3+
  29601. // v = 1h 8+ 3+
  29602. // v = 0h
  29603. // u = 0 1 2 3 4 5 6 *a
  29604. // Face layout on texture UV mapping
  29605. // ============
  29606. // \ 4 /\ 16 / ======
  29607. // \ / \ / /\ 11 /
  29608. // \/ 7 \/ / \ /
  29609. // ======= / 10 \/
  29610. // /\ 17 /\ =======
  29611. // / \ / \ \ 15 /\
  29612. // / 8 \/ 12 \ \ / \
  29613. // ============ \/ 6 \
  29614. // \ 18 /\ ============
  29615. // \ / \ \ 5 /\ 0 /
  29616. // \/ 13 \ \ / \ /
  29617. // ======= \/ 1 \/
  29618. // =============
  29619. // /\ 19 /\ 2 /\
  29620. // / \ / \ / \
  29621. // / 14 \/ 9 \/ 3 \
  29622. // ===================
  29623. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  29624. var ustep = 138 / 1024;
  29625. var vstep = 239 / 1024;
  29626. var uoffset = 60 / 1024;
  29627. var voffset = 26 / 1024;
  29628. // Second island should have margin, not to touch the first island
  29629. // avoid any borderline artefact in pixel rounding
  29630. var island_u_offset = -40 / 1024;
  29631. var island_v_offset = +20 / 1024;
  29632. // face is either island 0 or 1 :
  29633. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  29634. var island = [
  29635. 0, 0, 0, 0, 1,
  29636. 0, 0, 1, 1, 0,
  29637. 0, 0, 1, 1, 0,
  29638. 0, 1, 1, 1, 0 // 15 - 19
  29639. ];
  29640. var indices = new Array();
  29641. var positions = new Array();
  29642. var normals = new Array();
  29643. var uvs = new Array();
  29644. var current_indice = 0;
  29645. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  29646. var face_vertex_pos = new Array(3);
  29647. var face_vertex_uv = new Array(3);
  29648. var v012;
  29649. for (v012 = 0; v012 < 3; v012++) {
  29650. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  29651. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  29652. }
  29653. // create all with normals
  29654. for (var face = 0; face < 20; face++) {
  29655. // 3 vertex per face
  29656. for (v012 = 0; v012 < 3; v012++) {
  29657. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  29658. var v_id = ico_indices[3 * face + v012];
  29659. // vertex have 3D position (x,y,z)
  29660. 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]);
  29661. // Normalize to get normal, then scale to radius
  29662. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  29663. // uv Coordinates from vertex ID
  29664. 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);
  29665. }
  29666. // Subdivide the face (interpolate pos, norm, uv)
  29667. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  29668. // - norm is linear interpolation of vertex corner normal
  29669. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  29670. // - uv is linear interpolation
  29671. //
  29672. // Topology is as below for sub-divide by 2
  29673. // vertex shown as v0,v1,v2
  29674. // interp index is i1 to progress in range [v0,v1[
  29675. // interp index is i2 to progress in range [v0,v2[
  29676. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  29677. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29678. //
  29679. //
  29680. // i2 v2
  29681. // ^ ^
  29682. // / / \
  29683. // / / \
  29684. // / / \
  29685. // / / (0,1) \
  29686. // / #---------\
  29687. // / / \ (0,0)'/ \
  29688. // / / \ / \
  29689. // / / \ / \
  29690. // / / (0,0) \ / (1,0) \
  29691. // / #---------#---------\
  29692. // v0 v1
  29693. //
  29694. // --------------------> i1
  29695. //
  29696. // interp of (i1,i2):
  29697. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  29698. // along i1 : lerp(x0,x1, i1/(S-i2))
  29699. //
  29700. // centroid of triangle is needed to get help normal computation
  29701. // (c1,c2) are used for centroid location
  29702. var interp_vertex = function (i1, i2, c1, c2) {
  29703. // vertex is interpolated from
  29704. // - face_vertex_pos[0..2]
  29705. // - face_vertex_uv[0..2]
  29706. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  29707. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  29708. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  29709. pos_interp.normalize();
  29710. var vertex_normal;
  29711. if (flat) {
  29712. // in flat mode, recalculate normal as face centroid normal
  29713. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  29714. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  29715. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  29716. }
  29717. else {
  29718. // in smooth mode, recalculate normal from each single vertex position
  29719. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  29720. }
  29721. // Vertex normal need correction due to X,Y,Z radius scaling
  29722. vertex_normal.x /= radiusX;
  29723. vertex_normal.y /= radiusY;
  29724. vertex_normal.z /= radiusZ;
  29725. vertex_normal.normalize();
  29726. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  29727. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  29728. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  29729. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  29730. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  29731. uvs.push(uv_interp.x, uv_interp.y);
  29732. // push each vertex has member of a face
  29733. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  29734. indices.push(current_indice);
  29735. current_indice++;
  29736. };
  29737. for (var i2 = 0; i2 < subdivisions; i2++) {
  29738. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  29739. // face : (i1,i2) for /\ :
  29740. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  29741. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29742. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29743. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  29744. if (i1 + i2 + 1 < subdivisions) {
  29745. // face : (i1,i2)' for \/ :
  29746. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  29747. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29748. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29749. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  29750. }
  29751. }
  29752. }
  29753. }
  29754. // Sides
  29755. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29756. // Result
  29757. var vertexData = new VertexData();
  29758. vertexData.indices = indices;
  29759. vertexData.positions = positions;
  29760. vertexData.normals = normals;
  29761. vertexData.uvs = uvs;
  29762. return vertexData;
  29763. };
  29764. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  29765. /**
  29766. * Creates the VertexData of the Polyhedron.
  29767. */
  29768. VertexData.CreatePolyhedron = function (options) {
  29769. // provided polyhedron types :
  29770. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  29771. // 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)
  29772. var polyhedra = [];
  29773. 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]] };
  29774. 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]] };
  29775. polyhedra[2] = {
  29776. 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]],
  29777. 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]]
  29778. };
  29779. polyhedra[3] = {
  29780. 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]],
  29781. 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]]
  29782. };
  29783. polyhedra[4] = {
  29784. 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]],
  29785. 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]]
  29786. };
  29787. 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]] };
  29788. 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]] };
  29789. 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]] };
  29790. 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]] };
  29791. 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]] };
  29792. 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]] };
  29793. 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]] };
  29794. 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]] };
  29795. 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]] };
  29796. polyhedra[14] = {
  29797. 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]],
  29798. 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]]
  29799. };
  29800. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  29801. var size = options.size;
  29802. var sizeX = options.sizeX || size || 1;
  29803. var sizeY = options.sizeY || size || 1;
  29804. var sizeZ = options.sizeZ || size || 1;
  29805. var data = options.custom || polyhedra[type];
  29806. var nbfaces = data.face.length;
  29807. var faceUV = options.faceUV || new Array(nbfaces);
  29808. var faceColors = options.faceColors;
  29809. var flat = (options.flat === undefined) ? true : options.flat;
  29810. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29811. var positions = new Array();
  29812. var indices = new Array();
  29813. var normals = new Array();
  29814. var uvs = new Array();
  29815. var colors = new Array();
  29816. var index = 0;
  29817. var faceIdx = 0; // face cursor in the array "indexes"
  29818. var indexes = new Array();
  29819. var i = 0;
  29820. var f = 0;
  29821. var u, v, ang, x, y, tmp;
  29822. // default face colors and UV if undefined
  29823. if (flat) {
  29824. for (f = 0; f < nbfaces; f++) {
  29825. if (faceColors && faceColors[f] === undefined) {
  29826. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29827. }
  29828. if (faceUV && faceUV[f] === undefined) {
  29829. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29830. }
  29831. }
  29832. }
  29833. if (!flat) {
  29834. for (i = 0; i < data.vertex.length; i++) {
  29835. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  29836. uvs.push(0, 0);
  29837. }
  29838. for (f = 0; f < nbfaces; f++) {
  29839. for (i = 0; i < data.face[f].length - 2; i++) {
  29840. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  29841. }
  29842. }
  29843. }
  29844. else {
  29845. for (f = 0; f < nbfaces; f++) {
  29846. var fl = data.face[f].length; // number of vertices of the current face
  29847. ang = 2 * Math.PI / fl;
  29848. x = 0.5 * Math.tan(ang / 2);
  29849. y = 0.5;
  29850. // positions, uvs, colors
  29851. for (i = 0; i < fl; i++) {
  29852. // positions
  29853. 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);
  29854. indexes.push(index);
  29855. index++;
  29856. // uvs
  29857. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  29858. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  29859. uvs.push(u, v);
  29860. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  29861. y = x * Math.sin(ang) + y * Math.cos(ang);
  29862. x = tmp;
  29863. // colors
  29864. if (faceColors) {
  29865. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  29866. }
  29867. }
  29868. // indices from indexes
  29869. for (i = 0; i < fl - 2; i++) {
  29870. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  29871. }
  29872. faceIdx += fl;
  29873. }
  29874. }
  29875. VertexData.ComputeNormals(positions, indices, normals);
  29876. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29877. var vertexData = new VertexData();
  29878. vertexData.positions = positions;
  29879. vertexData.indices = indices;
  29880. vertexData.normals = normals;
  29881. vertexData.uvs = uvs;
  29882. if (faceColors && flat) {
  29883. vertexData.colors = colors;
  29884. }
  29885. return vertexData;
  29886. };
  29887. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  29888. /**
  29889. * Creates the VertexData of the Torus Knot.
  29890. */
  29891. VertexData.CreateTorusKnot = function (options) {
  29892. var indices = new Array();
  29893. var positions = new Array();
  29894. var normals = new Array();
  29895. var uvs = new Array();
  29896. var radius = options.radius || 2;
  29897. var tube = options.tube || 0.5;
  29898. var radialSegments = options.radialSegments || 32;
  29899. var tubularSegments = options.tubularSegments || 32;
  29900. var p = options.p || 2;
  29901. var q = options.q || 3;
  29902. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29903. // Helper
  29904. var getPos = function (angle) {
  29905. var cu = Math.cos(angle);
  29906. var su = Math.sin(angle);
  29907. var quOverP = q / p * angle;
  29908. var cs = Math.cos(quOverP);
  29909. var tx = radius * (2 + cs) * 0.5 * cu;
  29910. var ty = radius * (2 + cs) * su * 0.5;
  29911. var tz = radius * Math.sin(quOverP) * 0.5;
  29912. return new BABYLON.Vector3(tx, ty, tz);
  29913. };
  29914. // Vertices
  29915. var i;
  29916. var j;
  29917. for (i = 0; i <= radialSegments; i++) {
  29918. var modI = i % radialSegments;
  29919. var u = modI / radialSegments * 2 * p * Math.PI;
  29920. var p1 = getPos(u);
  29921. var p2 = getPos(u + 0.01);
  29922. var tang = p2.subtract(p1);
  29923. var n = p2.add(p1);
  29924. var bitan = BABYLON.Vector3.Cross(tang, n);
  29925. n = BABYLON.Vector3.Cross(bitan, tang);
  29926. bitan.normalize();
  29927. n.normalize();
  29928. for (j = 0; j < tubularSegments; j++) {
  29929. var modJ = j % tubularSegments;
  29930. var v = modJ / tubularSegments * 2 * Math.PI;
  29931. var cx = -tube * Math.cos(v);
  29932. var cy = tube * Math.sin(v);
  29933. positions.push(p1.x + cx * n.x + cy * bitan.x);
  29934. positions.push(p1.y + cx * n.y + cy * bitan.y);
  29935. positions.push(p1.z + cx * n.z + cy * bitan.z);
  29936. uvs.push(i / radialSegments);
  29937. uvs.push(j / tubularSegments);
  29938. }
  29939. }
  29940. for (i = 0; i < radialSegments; i++) {
  29941. for (j = 0; j < tubularSegments; j++) {
  29942. var jNext = (j + 1) % tubularSegments;
  29943. var a = i * tubularSegments + j;
  29944. var b = (i + 1) * tubularSegments + j;
  29945. var c = (i + 1) * tubularSegments + jNext;
  29946. var d = i * tubularSegments + jNext;
  29947. indices.push(d);
  29948. indices.push(b);
  29949. indices.push(a);
  29950. indices.push(d);
  29951. indices.push(c);
  29952. indices.push(b);
  29953. }
  29954. }
  29955. // Normals
  29956. VertexData.ComputeNormals(positions, indices, normals);
  29957. // Sides
  29958. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29959. // Result
  29960. var vertexData = new VertexData();
  29961. vertexData.indices = indices;
  29962. vertexData.positions = positions;
  29963. vertexData.normals = normals;
  29964. vertexData.uvs = uvs;
  29965. return vertexData;
  29966. };
  29967. // Tools
  29968. /**
  29969. * @param {any} - positions (number[] or Float32Array)
  29970. * @param {any} - indices (number[] or Uint16Array)
  29971. * @param {any} - normals (number[] or Float32Array)
  29972. * options (optional) :
  29973. * facetPositions : optional array of facet positions (vector3)
  29974. * facetNormals : optional array of facet normals (vector3)
  29975. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  29976. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  29977. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  29978. * bbSize : optional bounding box size data, required for facetPartitioning computation
  29979. * bInfo : optional bounding info, required for facetPartitioning computation
  29980. */
  29981. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  29982. // temporary scalar variables
  29983. var index = 0; // facet index
  29984. var p1p2x = 0.0; // p1p2 vector x coordinate
  29985. var p1p2y = 0.0; // p1p2 vector y coordinate
  29986. var p1p2z = 0.0; // p1p2 vector z coordinate
  29987. var p3p2x = 0.0; // p3p2 vector x coordinate
  29988. var p3p2y = 0.0; // p3p2 vector y coordinate
  29989. var p3p2z = 0.0; // p3p2 vector z coordinate
  29990. var faceNormalx = 0.0; // facet normal x coordinate
  29991. var faceNormaly = 0.0; // facet normal y coordinate
  29992. var faceNormalz = 0.0; // facet normal z coordinate
  29993. var length = 0.0; // facet normal length before normalization
  29994. var v1x = 0; // vector1 x index in the positions array
  29995. var v1y = 0; // vector1 y index in the positions array
  29996. var v1z = 0; // vector1 z index in the positions array
  29997. var v2x = 0; // vector2 x index in the positions array
  29998. var v2y = 0; // vector2 y index in the positions array
  29999. var v2z = 0; // vector2 z index in the positions array
  30000. var v3x = 0; // vector3 x index in the positions array
  30001. var v3y = 0; // vector3 y index in the positions array
  30002. var v3z = 0; // vector3 z index in the positions array
  30003. var computeFacetNormals = false;
  30004. var computeFacetPositions = false;
  30005. var computeFacetPartitioning = false;
  30006. var faceNormalSign = 1;
  30007. var ratio = 0;
  30008. if (options) {
  30009. computeFacetNormals = (options.facetNormals) ? true : false;
  30010. computeFacetPositions = (options.facetPositions) ? true : false;
  30011. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30012. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30013. ratio = options.ratio || 0;
  30014. }
  30015. // facetPartitioning reinit if needed
  30016. var xSubRatio = 0;
  30017. var ySubRatio = 0;
  30018. var zSubRatio = 0;
  30019. var subSq = 0;
  30020. if (computeFacetPartitioning && options && options.bbSize) {
  30021. var ox = 0; // X partitioning index for facet position
  30022. var oy = 0; // Y partinioning index for facet position
  30023. var oz = 0; // Z partinioning index for facet position
  30024. var b1x = 0; // X partitioning index for facet v1 vertex
  30025. var b1y = 0; // Y partitioning index for facet v1 vertex
  30026. var b1z = 0; // z partitioning index for facet v1 vertex
  30027. var b2x = 0; // X partitioning index for facet v2 vertex
  30028. var b2y = 0; // Y partitioning index for facet v2 vertex
  30029. var b2z = 0; // Z partitioning index for facet v2 vertex
  30030. var b3x = 0; // X partitioning index for facet v3 vertex
  30031. var b3y = 0; // Y partitioning index for facet v3 vertex
  30032. var b3z = 0; // Z partitioning index for facet v3 vertex
  30033. var block_idx_o = 0; // facet barycenter block index
  30034. var block_idx_v1 = 0; // v1 vertex block index
  30035. var block_idx_v2 = 0; // v2 vertex block index
  30036. var block_idx_v3 = 0; // v3 vertex block index
  30037. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30038. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30039. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30040. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30041. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30042. subSq = options.subDiv.max * options.subDiv.max;
  30043. options.facetPartitioning.length = 0;
  30044. }
  30045. // reset the normals
  30046. for (index = 0; index < positions.length; index++) {
  30047. normals[index] = 0.0;
  30048. }
  30049. // Loop : 1 indice triplet = 1 facet
  30050. var nbFaces = indices.length / 3;
  30051. for (index = 0; index < nbFaces; index++) {
  30052. // get the indexes of the coordinates of each vertex of the facet
  30053. v1x = indices[index * 3] * 3;
  30054. v1y = v1x + 1;
  30055. v1z = v1x + 2;
  30056. v2x = indices[index * 3 + 1] * 3;
  30057. v2y = v2x + 1;
  30058. v2z = v2x + 2;
  30059. v3x = indices[index * 3 + 2] * 3;
  30060. v3y = v3x + 1;
  30061. v3z = v3x + 2;
  30062. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30063. p1p2y = positions[v1y] - positions[v2y];
  30064. p1p2z = positions[v1z] - positions[v2z];
  30065. p3p2x = positions[v3x] - positions[v2x];
  30066. p3p2y = positions[v3y] - positions[v2y];
  30067. p3p2z = positions[v3z] - positions[v2z];
  30068. // compute the face normal with the cross product
  30069. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30070. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30071. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30072. // normalize this normal and store it in the array facetData
  30073. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30074. length = (length === 0) ? 1.0 : length;
  30075. faceNormalx /= length;
  30076. faceNormaly /= length;
  30077. faceNormalz /= length;
  30078. if (computeFacetNormals && options) {
  30079. options.facetNormals[index].x = faceNormalx;
  30080. options.facetNormals[index].y = faceNormaly;
  30081. options.facetNormals[index].z = faceNormalz;
  30082. }
  30083. if (computeFacetPositions && options) {
  30084. // compute and the facet barycenter coordinates in the array facetPositions
  30085. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30086. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30087. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30088. }
  30089. if (computeFacetPartitioning && options) {
  30090. // store the facet indexes in arrays in the main facetPartitioning array :
  30091. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30092. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30093. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30094. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30095. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30096. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30097. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30098. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30099. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30100. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30101. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30102. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30103. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30104. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30105. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30106. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30107. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30108. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30109. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30110. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30111. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30112. // push each facet index in each block containing the vertex
  30113. options.facetPartitioning[block_idx_v1].push(index);
  30114. if (block_idx_v2 != block_idx_v1) {
  30115. options.facetPartitioning[block_idx_v2].push(index);
  30116. }
  30117. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30118. options.facetPartitioning[block_idx_v3].push(index);
  30119. }
  30120. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30121. options.facetPartitioning[block_idx_o].push(index);
  30122. }
  30123. }
  30124. // compute the normals anyway
  30125. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30126. normals[v1y] += faceNormaly;
  30127. normals[v1z] += faceNormalz;
  30128. normals[v2x] += faceNormalx;
  30129. normals[v2y] += faceNormaly;
  30130. normals[v2z] += faceNormalz;
  30131. normals[v3x] += faceNormalx;
  30132. normals[v3y] += faceNormaly;
  30133. normals[v3z] += faceNormalz;
  30134. }
  30135. // last normalization of each normal
  30136. for (index = 0; index < normals.length / 3; index++) {
  30137. faceNormalx = normals[index * 3];
  30138. faceNormaly = normals[index * 3 + 1];
  30139. faceNormalz = normals[index * 3 + 2];
  30140. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30141. length = (length === 0) ? 1.0 : length;
  30142. faceNormalx /= length;
  30143. faceNormaly /= length;
  30144. faceNormalz /= length;
  30145. normals[index * 3] = faceNormalx;
  30146. normals[index * 3 + 1] = faceNormaly;
  30147. normals[index * 3 + 2] = faceNormalz;
  30148. }
  30149. };
  30150. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30151. var li = indices.length;
  30152. var ln = normals.length;
  30153. var i;
  30154. var n;
  30155. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30156. switch (sideOrientation) {
  30157. case BABYLON.Mesh.FRONTSIDE:
  30158. // nothing changed
  30159. break;
  30160. case BABYLON.Mesh.BACKSIDE:
  30161. var tmp;
  30162. // indices
  30163. for (i = 0; i < li; i += 3) {
  30164. tmp = indices[i];
  30165. indices[i] = indices[i + 2];
  30166. indices[i + 2] = tmp;
  30167. }
  30168. // normals
  30169. for (n = 0; n < ln; n++) {
  30170. normals[n] = -normals[n];
  30171. }
  30172. break;
  30173. case BABYLON.Mesh.DOUBLESIDE:
  30174. // positions
  30175. var lp = positions.length;
  30176. var l = lp / 3;
  30177. for (var p = 0; p < lp; p++) {
  30178. positions[lp + p] = positions[p];
  30179. }
  30180. // indices
  30181. for (i = 0; i < li; i += 3) {
  30182. indices[i + li] = indices[i + 2] + l;
  30183. indices[i + 1 + li] = indices[i + 1] + l;
  30184. indices[i + 2 + li] = indices[i] + l;
  30185. }
  30186. // normals
  30187. for (n = 0; n < ln; n++) {
  30188. normals[ln + n] = -normals[n];
  30189. }
  30190. // uvs
  30191. var lu = uvs.length;
  30192. var u = 0;
  30193. for (u = 0; u < lu; u++) {
  30194. uvs[u + lu] = uvs[u];
  30195. }
  30196. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30197. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  30198. u = 0;
  30199. for (i = 0; i < lu / 2; i++) {
  30200. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  30201. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  30202. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  30203. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  30204. u += 2;
  30205. }
  30206. break;
  30207. }
  30208. };
  30209. /**
  30210. * Creates a new VertexData from the imported parameters.
  30211. */
  30212. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  30213. var vertexData = new VertexData();
  30214. // positions
  30215. var positions = parsedVertexData.positions;
  30216. if (positions) {
  30217. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  30218. }
  30219. // normals
  30220. var normals = parsedVertexData.normals;
  30221. if (normals) {
  30222. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  30223. }
  30224. // tangents
  30225. var tangents = parsedVertexData.tangents;
  30226. if (tangents) {
  30227. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  30228. }
  30229. // uvs
  30230. var uvs = parsedVertexData.uvs;
  30231. if (uvs) {
  30232. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  30233. }
  30234. // uv2s
  30235. var uv2s = parsedVertexData.uv2s;
  30236. if (uv2s) {
  30237. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  30238. }
  30239. // uv3s
  30240. var uv3s = parsedVertexData.uv3s;
  30241. if (uv3s) {
  30242. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  30243. }
  30244. // uv4s
  30245. var uv4s = parsedVertexData.uv4s;
  30246. if (uv4s) {
  30247. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  30248. }
  30249. // uv5s
  30250. var uv5s = parsedVertexData.uv5s;
  30251. if (uv5s) {
  30252. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  30253. }
  30254. // uv6s
  30255. var uv6s = parsedVertexData.uv6s;
  30256. if (uv6s) {
  30257. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  30258. }
  30259. // colors
  30260. var colors = parsedVertexData.colors;
  30261. if (colors) {
  30262. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  30263. }
  30264. // matricesIndices
  30265. var matricesIndices = parsedVertexData.matricesIndices;
  30266. if (matricesIndices) {
  30267. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  30268. }
  30269. // matricesWeights
  30270. var matricesWeights = parsedVertexData.matricesWeights;
  30271. if (matricesWeights) {
  30272. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  30273. }
  30274. // indices
  30275. var indices = parsedVertexData.indices;
  30276. if (indices) {
  30277. vertexData.indices = indices;
  30278. }
  30279. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  30280. };
  30281. return VertexData;
  30282. }());
  30283. BABYLON.VertexData = VertexData;
  30284. })(BABYLON || (BABYLON = {}));
  30285. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  30286. var BABYLON;
  30287. (function (BABYLON) {
  30288. var Geometry = /** @class */ (function () {
  30289. function Geometry(id, scene, vertexData, updatable, mesh) {
  30290. if (updatable === void 0) { updatable = false; }
  30291. if (mesh === void 0) { mesh = null; }
  30292. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30293. this._totalVertices = 0;
  30294. this._isDisposed = false;
  30295. this._indexBufferIsUpdatable = false;
  30296. this.id = id;
  30297. this._engine = scene.getEngine();
  30298. this._meshes = [];
  30299. this._scene = scene;
  30300. //Init vertex buffer cache
  30301. this._vertexBuffers = {};
  30302. this._indices = [];
  30303. this._updatable = updatable;
  30304. // vertexData
  30305. if (vertexData) {
  30306. this.setAllVerticesData(vertexData, updatable);
  30307. }
  30308. else {
  30309. this._totalVertices = 0;
  30310. this._indices = [];
  30311. }
  30312. if (this._engine.getCaps().vertexArrayObject) {
  30313. this._vertexArrayObjects = {};
  30314. }
  30315. // applyToMesh
  30316. if (mesh) {
  30317. if (mesh.getClassName() === "LinesMesh") {
  30318. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  30319. this.updateExtend();
  30320. }
  30321. this.applyToMesh(mesh);
  30322. mesh.computeWorldMatrix(true);
  30323. }
  30324. }
  30325. Object.defineProperty(Geometry.prototype, "boundingBias", {
  30326. /**
  30327. * 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
  30328. * @returns The Bias Vector
  30329. */
  30330. get: function () {
  30331. return this._boundingBias;
  30332. },
  30333. set: function (value) {
  30334. if (this._boundingBias && this._boundingBias.equals(value)) {
  30335. return;
  30336. }
  30337. this._boundingBias = value.clone();
  30338. this.updateBoundingInfo(true, null);
  30339. },
  30340. enumerable: true,
  30341. configurable: true
  30342. });
  30343. Geometry.CreateGeometryForMesh = function (mesh) {
  30344. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  30345. geometry.applyToMesh(mesh);
  30346. return geometry;
  30347. };
  30348. Object.defineProperty(Geometry.prototype, "extend", {
  30349. get: function () {
  30350. return this._extend;
  30351. },
  30352. enumerable: true,
  30353. configurable: true
  30354. });
  30355. Geometry.prototype.getScene = function () {
  30356. return this._scene;
  30357. };
  30358. Geometry.prototype.getEngine = function () {
  30359. return this._engine;
  30360. };
  30361. Geometry.prototype.isReady = function () {
  30362. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  30363. };
  30364. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  30365. get: function () {
  30366. for (var index = 0; index < this._meshes.length; index++) {
  30367. if (!this._meshes[index].doNotSerialize) {
  30368. return false;
  30369. }
  30370. }
  30371. return true;
  30372. },
  30373. enumerable: true,
  30374. configurable: true
  30375. });
  30376. Geometry.prototype._rebuild = function () {
  30377. if (this._vertexArrayObjects) {
  30378. this._vertexArrayObjects = {};
  30379. }
  30380. // Index buffer
  30381. if (this._meshes.length !== 0 && this._indices) {
  30382. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30383. }
  30384. // Vertex buffers
  30385. for (var key in this._vertexBuffers) {
  30386. var vertexBuffer = this._vertexBuffers[key];
  30387. vertexBuffer._rebuild();
  30388. }
  30389. };
  30390. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  30391. vertexData.applyToGeometry(this, updatable);
  30392. this.notifyUpdate();
  30393. };
  30394. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  30395. if (updatable === void 0) { updatable = false; }
  30396. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  30397. this.setVerticesBuffer(buffer);
  30398. };
  30399. Geometry.prototype.removeVerticesData = function (kind) {
  30400. if (this._vertexBuffers[kind]) {
  30401. this._vertexBuffers[kind].dispose();
  30402. delete this._vertexBuffers[kind];
  30403. }
  30404. };
  30405. Geometry.prototype.setVerticesBuffer = function (buffer) {
  30406. var kind = buffer.getKind();
  30407. if (this._vertexBuffers[kind]) {
  30408. this._vertexBuffers[kind].dispose();
  30409. }
  30410. this._vertexBuffers[kind] = buffer;
  30411. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30412. var data = buffer.getData();
  30413. var stride = buffer.getStrideSize();
  30414. this._totalVertices = data.length / stride;
  30415. this.updateExtend(data, stride);
  30416. this._resetPointsArrayCache();
  30417. var meshes = this._meshes;
  30418. var numOfMeshes = meshes.length;
  30419. for (var index = 0; index < numOfMeshes; index++) {
  30420. var mesh = meshes[index];
  30421. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30422. mesh._createGlobalSubMesh(false);
  30423. mesh.computeWorldMatrix(true);
  30424. }
  30425. }
  30426. this.notifyUpdate(kind);
  30427. if (this._vertexArrayObjects) {
  30428. this._disposeVertexArrayObjects();
  30429. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  30430. }
  30431. };
  30432. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  30433. var vertexBuffer = this.getVertexBuffer(kind);
  30434. if (!vertexBuffer) {
  30435. return;
  30436. }
  30437. vertexBuffer.updateDirectly(data, offset);
  30438. this.notifyUpdate(kind);
  30439. };
  30440. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  30441. if (updateExtends === void 0) { updateExtends = false; }
  30442. var vertexBuffer = this.getVertexBuffer(kind);
  30443. if (!vertexBuffer) {
  30444. return;
  30445. }
  30446. vertexBuffer.update(data);
  30447. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30448. var stride = vertexBuffer.getStrideSize();
  30449. this._totalVertices = data.length / stride;
  30450. this.updateBoundingInfo(updateExtends, data);
  30451. }
  30452. this.notifyUpdate(kind);
  30453. };
  30454. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  30455. if (updateExtends) {
  30456. this.updateExtend(data);
  30457. }
  30458. var meshes = this._meshes;
  30459. var numOfMeshes = meshes.length;
  30460. this._resetPointsArrayCache();
  30461. for (var index = 0; index < numOfMeshes; index++) {
  30462. var mesh = meshes[index];
  30463. if (updateExtends) {
  30464. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30465. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  30466. var subMesh = mesh.subMeshes[subIndex];
  30467. subMesh.refreshBoundingInfo();
  30468. }
  30469. }
  30470. }
  30471. };
  30472. Geometry.prototype._bind = function (effect, indexToBind) {
  30473. if (!effect) {
  30474. return;
  30475. }
  30476. if (indexToBind === undefined) {
  30477. indexToBind = this._indexBuffer;
  30478. }
  30479. var vbs = this.getVertexBuffers();
  30480. if (!vbs) {
  30481. return;
  30482. }
  30483. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  30484. this._engine.bindBuffers(vbs, indexToBind, effect);
  30485. return;
  30486. }
  30487. // Using VAO
  30488. if (!this._vertexArrayObjects[effect.key]) {
  30489. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  30490. }
  30491. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  30492. };
  30493. Geometry.prototype.getTotalVertices = function () {
  30494. if (!this.isReady()) {
  30495. return 0;
  30496. }
  30497. return this._totalVertices;
  30498. };
  30499. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30500. var vertexBuffer = this.getVertexBuffer(kind);
  30501. if (!vertexBuffer) {
  30502. return null;
  30503. }
  30504. var orig = vertexBuffer.getData();
  30505. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  30506. return orig;
  30507. }
  30508. else {
  30509. var len = orig.length;
  30510. var copy = [];
  30511. for (var i = 0; i < len; i++) {
  30512. copy.push(orig[i]);
  30513. }
  30514. return copy;
  30515. }
  30516. };
  30517. /**
  30518. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30519. * Possible `kind` values :
  30520. * - BABYLON.VertexBuffer.PositionKind
  30521. * - BABYLON.VertexBuffer.UVKind
  30522. * - BABYLON.VertexBuffer.UV2Kind
  30523. * - BABYLON.VertexBuffer.UV3Kind
  30524. * - BABYLON.VertexBuffer.UV4Kind
  30525. * - BABYLON.VertexBuffer.UV5Kind
  30526. * - BABYLON.VertexBuffer.UV6Kind
  30527. * - BABYLON.VertexBuffer.ColorKind
  30528. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30529. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30530. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30531. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30532. */
  30533. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  30534. var vb = this._vertexBuffers[kind];
  30535. if (!vb) {
  30536. return false;
  30537. }
  30538. return vb.isUpdatable();
  30539. };
  30540. Geometry.prototype.getVertexBuffer = function (kind) {
  30541. if (!this.isReady()) {
  30542. return null;
  30543. }
  30544. return this._vertexBuffers[kind];
  30545. };
  30546. Geometry.prototype.getVertexBuffers = function () {
  30547. if (!this.isReady()) {
  30548. return null;
  30549. }
  30550. return this._vertexBuffers;
  30551. };
  30552. Geometry.prototype.isVerticesDataPresent = function (kind) {
  30553. if (!this._vertexBuffers) {
  30554. if (this._delayInfo) {
  30555. return this._delayInfo.indexOf(kind) !== -1;
  30556. }
  30557. return false;
  30558. }
  30559. return this._vertexBuffers[kind] !== undefined;
  30560. };
  30561. Geometry.prototype.getVerticesDataKinds = function () {
  30562. var result = [];
  30563. var kind;
  30564. if (!this._vertexBuffers && this._delayInfo) {
  30565. for (kind in this._delayInfo) {
  30566. result.push(kind);
  30567. }
  30568. }
  30569. else {
  30570. for (kind in this._vertexBuffers) {
  30571. result.push(kind);
  30572. }
  30573. }
  30574. return result;
  30575. };
  30576. Geometry.prototype.updateIndices = function (indices, offset) {
  30577. if (!this._indexBuffer) {
  30578. return;
  30579. }
  30580. if (!this._indexBufferIsUpdatable) {
  30581. this.setIndices(indices, null, true);
  30582. }
  30583. else {
  30584. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  30585. }
  30586. };
  30587. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  30588. if (totalVertices === void 0) { totalVertices = null; }
  30589. if (updatable === void 0) { updatable = false; }
  30590. if (this._indexBuffer) {
  30591. this._engine._releaseBuffer(this._indexBuffer);
  30592. }
  30593. this._disposeVertexArrayObjects();
  30594. this._indices = indices;
  30595. this._indexBufferIsUpdatable = updatable;
  30596. if (this._meshes.length !== 0 && this._indices) {
  30597. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  30598. }
  30599. if (totalVertices != undefined) {
  30600. this._totalVertices = totalVertices;
  30601. }
  30602. var meshes = this._meshes;
  30603. var numOfMeshes = meshes.length;
  30604. for (var index = 0; index < numOfMeshes; index++) {
  30605. meshes[index]._createGlobalSubMesh(true);
  30606. }
  30607. this.notifyUpdate();
  30608. };
  30609. Geometry.prototype.getTotalIndices = function () {
  30610. if (!this.isReady()) {
  30611. return 0;
  30612. }
  30613. return this._indices.length;
  30614. };
  30615. Geometry.prototype.getIndices = function (copyWhenShared) {
  30616. if (!this.isReady()) {
  30617. return null;
  30618. }
  30619. var orig = this._indices;
  30620. if (!copyWhenShared || this._meshes.length === 1) {
  30621. return orig;
  30622. }
  30623. else {
  30624. var len = orig.length;
  30625. var copy = [];
  30626. for (var i = 0; i < len; i++) {
  30627. copy.push(orig[i]);
  30628. }
  30629. return copy;
  30630. }
  30631. };
  30632. Geometry.prototype.getIndexBuffer = function () {
  30633. if (!this.isReady()) {
  30634. return null;
  30635. }
  30636. return this._indexBuffer;
  30637. };
  30638. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  30639. if (effect === void 0) { effect = null; }
  30640. if (!effect || !this._vertexArrayObjects) {
  30641. return;
  30642. }
  30643. if (this._vertexArrayObjects[effect.key]) {
  30644. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  30645. delete this._vertexArrayObjects[effect.key];
  30646. }
  30647. };
  30648. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  30649. var meshes = this._meshes;
  30650. var index = meshes.indexOf(mesh);
  30651. if (index === -1) {
  30652. return;
  30653. }
  30654. meshes.splice(index, 1);
  30655. mesh._geometry = null;
  30656. if (meshes.length === 0 && shouldDispose) {
  30657. this.dispose();
  30658. }
  30659. };
  30660. Geometry.prototype.applyToMesh = function (mesh) {
  30661. if (mesh._geometry === this) {
  30662. return;
  30663. }
  30664. var previousGeometry = mesh._geometry;
  30665. if (previousGeometry) {
  30666. previousGeometry.releaseForMesh(mesh);
  30667. }
  30668. var meshes = this._meshes;
  30669. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  30670. mesh._geometry = this;
  30671. this._scene.pushGeometry(this);
  30672. meshes.push(mesh);
  30673. if (this.isReady()) {
  30674. this._applyToMesh(mesh);
  30675. }
  30676. else {
  30677. mesh._boundingInfo = this._boundingInfo;
  30678. }
  30679. };
  30680. Geometry.prototype.updateExtend = function (data, stride) {
  30681. if (data === void 0) { data = null; }
  30682. if (!data) {
  30683. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  30684. }
  30685. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  30686. };
  30687. Geometry.prototype._applyToMesh = function (mesh) {
  30688. var numOfMeshes = this._meshes.length;
  30689. // vertexBuffers
  30690. for (var kind in this._vertexBuffers) {
  30691. if (numOfMeshes === 1) {
  30692. this._vertexBuffers[kind].create();
  30693. }
  30694. var buffer = this._vertexBuffers[kind].getBuffer();
  30695. if (buffer)
  30696. buffer.references = numOfMeshes;
  30697. if (kind === BABYLON.VertexBuffer.PositionKind) {
  30698. if (!this._extend) {
  30699. this.updateExtend(this._vertexBuffers[kind].getData());
  30700. }
  30701. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30702. mesh._createGlobalSubMesh(false);
  30703. //bounding info was just created again, world matrix should be applied again.
  30704. mesh._updateBoundingInfo();
  30705. }
  30706. }
  30707. // indexBuffer
  30708. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  30709. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  30710. }
  30711. if (this._indexBuffer) {
  30712. this._indexBuffer.references = numOfMeshes;
  30713. }
  30714. };
  30715. Geometry.prototype.notifyUpdate = function (kind) {
  30716. if (this.onGeometryUpdated) {
  30717. this.onGeometryUpdated(this, kind);
  30718. }
  30719. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  30720. var mesh = _a[_i];
  30721. mesh._markSubMeshesAsAttributesDirty();
  30722. }
  30723. };
  30724. Geometry.prototype.load = function (scene, onLoaded) {
  30725. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  30726. return;
  30727. }
  30728. if (this.isReady()) {
  30729. if (onLoaded) {
  30730. onLoaded();
  30731. }
  30732. return;
  30733. }
  30734. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  30735. this._queueLoad(scene, onLoaded);
  30736. };
  30737. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  30738. var _this = this;
  30739. if (!this.delayLoadingFile) {
  30740. return;
  30741. }
  30742. scene._addPendingData(this);
  30743. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  30744. if (!_this._delayLoadingFunction) {
  30745. return;
  30746. }
  30747. _this._delayLoadingFunction(JSON.parse(data), _this);
  30748. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30749. _this._delayInfo = [];
  30750. scene._removePendingData(_this);
  30751. var meshes = _this._meshes;
  30752. var numOfMeshes = meshes.length;
  30753. for (var index = 0; index < numOfMeshes; index++) {
  30754. _this._applyToMesh(meshes[index]);
  30755. }
  30756. if (onLoaded) {
  30757. onLoaded();
  30758. }
  30759. }, function () { }, scene.database);
  30760. };
  30761. /**
  30762. * Invert the geometry to move from a right handed system to a left handed one.
  30763. */
  30764. Geometry.prototype.toLeftHanded = function () {
  30765. // Flip faces
  30766. var tIndices = this.getIndices(false);
  30767. if (tIndices != null && tIndices.length > 0) {
  30768. for (var i = 0; i < tIndices.length; i += 3) {
  30769. var tTemp = tIndices[i + 0];
  30770. tIndices[i + 0] = tIndices[i + 2];
  30771. tIndices[i + 2] = tTemp;
  30772. }
  30773. this.setIndices(tIndices);
  30774. }
  30775. // Negate position.z
  30776. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  30777. if (tPositions != null && tPositions.length > 0) {
  30778. for (var i = 0; i < tPositions.length; i += 3) {
  30779. tPositions[i + 2] = -tPositions[i + 2];
  30780. }
  30781. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  30782. }
  30783. // Negate normal.z
  30784. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  30785. if (tNormals != null && tNormals.length > 0) {
  30786. for (var i = 0; i < tNormals.length; i += 3) {
  30787. tNormals[i + 2] = -tNormals[i + 2];
  30788. }
  30789. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  30790. }
  30791. };
  30792. // Cache
  30793. Geometry.prototype._resetPointsArrayCache = function () {
  30794. this._positions = null;
  30795. };
  30796. Geometry.prototype._generatePointsArray = function () {
  30797. if (this._positions)
  30798. return true;
  30799. this._positions = [];
  30800. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30801. if (!data) {
  30802. return false;
  30803. }
  30804. for (var index = 0; index < data.length; index += 3) {
  30805. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  30806. }
  30807. return true;
  30808. };
  30809. Geometry.prototype.isDisposed = function () {
  30810. return this._isDisposed;
  30811. };
  30812. Geometry.prototype._disposeVertexArrayObjects = function () {
  30813. if (this._vertexArrayObjects) {
  30814. for (var kind in this._vertexArrayObjects) {
  30815. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  30816. }
  30817. this._vertexArrayObjects = {};
  30818. }
  30819. };
  30820. Geometry.prototype.dispose = function () {
  30821. var meshes = this._meshes;
  30822. var numOfMeshes = meshes.length;
  30823. var index;
  30824. for (index = 0; index < numOfMeshes; index++) {
  30825. this.releaseForMesh(meshes[index]);
  30826. }
  30827. this._meshes = [];
  30828. this._disposeVertexArrayObjects();
  30829. for (var kind in this._vertexBuffers) {
  30830. this._vertexBuffers[kind].dispose();
  30831. }
  30832. this._vertexBuffers = {};
  30833. this._totalVertices = 0;
  30834. if (this._indexBuffer) {
  30835. this._engine._releaseBuffer(this._indexBuffer);
  30836. }
  30837. this._indexBuffer = null;
  30838. this._indices = [];
  30839. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30840. this.delayLoadingFile = null;
  30841. this._delayLoadingFunction = null;
  30842. this._delayInfo = [];
  30843. this._boundingInfo = null;
  30844. this._scene.removeGeometry(this);
  30845. this._isDisposed = true;
  30846. };
  30847. Geometry.prototype.copy = function (id) {
  30848. var vertexData = new BABYLON.VertexData();
  30849. vertexData.indices = [];
  30850. var indices = this.getIndices();
  30851. if (indices) {
  30852. for (var index = 0; index < indices.length; index++) {
  30853. vertexData.indices.push(indices[index]);
  30854. }
  30855. }
  30856. var updatable = false;
  30857. var stopChecking = false;
  30858. var kind;
  30859. for (kind in this._vertexBuffers) {
  30860. // using slice() to make a copy of the array and not just reference it
  30861. var data = this.getVerticesData(kind);
  30862. if (data instanceof Float32Array) {
  30863. vertexData.set(new Float32Array(data), kind);
  30864. }
  30865. else {
  30866. vertexData.set(data.slice(0), kind);
  30867. }
  30868. if (!stopChecking) {
  30869. var vb = this.getVertexBuffer(kind);
  30870. if (vb) {
  30871. updatable = vb.isUpdatable();
  30872. stopChecking = !updatable;
  30873. }
  30874. }
  30875. }
  30876. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  30877. geometry.delayLoadState = this.delayLoadState;
  30878. geometry.delayLoadingFile = this.delayLoadingFile;
  30879. geometry._delayLoadingFunction = this._delayLoadingFunction;
  30880. for (kind in this._delayInfo) {
  30881. geometry._delayInfo = geometry._delayInfo || [];
  30882. geometry._delayInfo.push(kind);
  30883. }
  30884. // Bounding info
  30885. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  30886. return geometry;
  30887. };
  30888. Geometry.prototype.serialize = function () {
  30889. var serializationObject = {};
  30890. serializationObject.id = this.id;
  30891. serializationObject.updatable = this._updatable;
  30892. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  30893. serializationObject.tags = BABYLON.Tags.GetTags(this);
  30894. }
  30895. return serializationObject;
  30896. };
  30897. Geometry.prototype.toNumberArray = function (origin) {
  30898. if (Array.isArray(origin)) {
  30899. return origin;
  30900. }
  30901. else {
  30902. return Array.prototype.slice.call(origin);
  30903. }
  30904. };
  30905. Geometry.prototype.serializeVerticeData = function () {
  30906. var serializationObject = this.serialize();
  30907. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30908. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  30909. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30910. serializationObject.positions._updatable = true;
  30911. }
  30912. }
  30913. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30914. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  30915. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30916. serializationObject.normals._updatable = true;
  30917. }
  30918. }
  30919. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30920. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  30921. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  30922. serializationObject.uvs._updatable = true;
  30923. }
  30924. }
  30925. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30926. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  30927. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  30928. serializationObject.uv2s._updatable = true;
  30929. }
  30930. }
  30931. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30932. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  30933. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  30934. serializationObject.uv3s._updatable = true;
  30935. }
  30936. }
  30937. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30938. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  30939. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  30940. serializationObject.uv4s._updatable = true;
  30941. }
  30942. }
  30943. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30944. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  30945. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  30946. serializationObject.uv5s._updatable = true;
  30947. }
  30948. }
  30949. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30950. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  30951. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  30952. serializationObject.uv6s._updatable = true;
  30953. }
  30954. }
  30955. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30956. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  30957. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  30958. serializationObject.colors._updatable = true;
  30959. }
  30960. }
  30961. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30962. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  30963. serializationObject.matricesIndices._isExpanded = true;
  30964. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30965. serializationObject.matricesIndices._updatable = true;
  30966. }
  30967. }
  30968. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30969. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  30970. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30971. serializationObject.matricesWeights._updatable = true;
  30972. }
  30973. }
  30974. serializationObject.indices = this.toNumberArray(this.getIndices());
  30975. return serializationObject;
  30976. };
  30977. // Statics
  30978. Geometry.ExtractFromMesh = function (mesh, id) {
  30979. var geometry = mesh._geometry;
  30980. if (!geometry) {
  30981. return null;
  30982. }
  30983. return geometry.copy(id);
  30984. };
  30985. /**
  30986. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  30987. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  30988. * Be aware Math.random() could cause collisions, but:
  30989. * "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"
  30990. */
  30991. Geometry.RandomId = function () {
  30992. return BABYLON.Tools.RandomId();
  30993. };
  30994. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  30995. var scene = mesh.getScene();
  30996. // Geometry
  30997. var geometryId = parsedGeometry.geometryId;
  30998. if (geometryId) {
  30999. var geometry = scene.getGeometryByID(geometryId);
  31000. if (geometry) {
  31001. geometry.applyToMesh(mesh);
  31002. }
  31003. }
  31004. else if (parsedGeometry instanceof ArrayBuffer) {
  31005. var binaryInfo = mesh._binaryInfo;
  31006. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31007. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31008. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31009. }
  31010. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31011. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31012. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31013. }
  31014. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31015. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31016. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31017. }
  31018. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31019. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31020. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31021. }
  31022. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31023. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31024. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31025. }
  31026. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31027. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31028. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31029. }
  31030. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31031. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31032. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31033. }
  31034. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31035. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31036. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31037. }
  31038. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31039. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31040. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31041. }
  31042. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31043. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31044. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31045. }
  31046. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31047. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31048. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31049. }
  31050. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31051. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31052. mesh.setIndices(indicesData, null);
  31053. }
  31054. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31055. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31056. mesh.subMeshes = [];
  31057. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31058. var materialIndex = subMeshesData[(i * 5) + 0];
  31059. var verticesStart = subMeshesData[(i * 5) + 1];
  31060. var verticesCount = subMeshesData[(i * 5) + 2];
  31061. var indexStart = subMeshesData[(i * 5) + 3];
  31062. var indexCount = subMeshesData[(i * 5) + 4];
  31063. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31064. }
  31065. }
  31066. }
  31067. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31068. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31069. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31070. if (parsedGeometry.uvs) {
  31071. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31072. }
  31073. if (parsedGeometry.uvs2) {
  31074. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31075. }
  31076. if (parsedGeometry.uvs3) {
  31077. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31078. }
  31079. if (parsedGeometry.uvs4) {
  31080. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31081. }
  31082. if (parsedGeometry.uvs5) {
  31083. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31084. }
  31085. if (parsedGeometry.uvs6) {
  31086. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31087. }
  31088. if (parsedGeometry.colors) {
  31089. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31090. }
  31091. if (parsedGeometry.matricesIndices) {
  31092. if (!parsedGeometry.matricesIndices._isExpanded) {
  31093. var floatIndices = [];
  31094. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31095. var matricesIndex = parsedGeometry.matricesIndices[i];
  31096. floatIndices.push(matricesIndex & 0x000000FF);
  31097. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31098. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31099. floatIndices.push(matricesIndex >> 24);
  31100. }
  31101. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31102. }
  31103. else {
  31104. delete parsedGeometry.matricesIndices._isExpanded;
  31105. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31106. }
  31107. }
  31108. if (parsedGeometry.matricesIndicesExtra) {
  31109. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31110. var floatIndices = [];
  31111. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31112. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31113. floatIndices.push(matricesIndex & 0x000000FF);
  31114. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31115. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31116. floatIndices.push(matricesIndex >> 24);
  31117. }
  31118. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31119. }
  31120. else {
  31121. delete parsedGeometry.matricesIndices._isExpanded;
  31122. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31123. }
  31124. }
  31125. if (parsedGeometry.matricesWeights) {
  31126. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31127. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31128. }
  31129. if (parsedGeometry.matricesWeightsExtra) {
  31130. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31131. }
  31132. mesh.setIndices(parsedGeometry.indices, null);
  31133. }
  31134. // SubMeshes
  31135. if (parsedGeometry.subMeshes) {
  31136. mesh.subMeshes = [];
  31137. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31138. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31139. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31140. }
  31141. }
  31142. // Flat shading
  31143. if (mesh._shouldGenerateFlatShading) {
  31144. mesh.convertToFlatShadedMesh();
  31145. delete mesh._shouldGenerateFlatShading;
  31146. }
  31147. // Update
  31148. mesh.computeWorldMatrix(true);
  31149. // Octree
  31150. if (scene['_selectionOctree']) {
  31151. scene['_selectionOctree'].addMesh(mesh);
  31152. }
  31153. };
  31154. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  31155. var epsilon = 1e-3;
  31156. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  31157. return;
  31158. }
  31159. var noInfluenceBoneIndex = 0.0;
  31160. if (parsedGeometry.skeletonId > -1) {
  31161. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  31162. if (!skeleton) {
  31163. return;
  31164. }
  31165. noInfluenceBoneIndex = skeleton.bones.length;
  31166. }
  31167. else {
  31168. return;
  31169. }
  31170. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31171. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  31172. var matricesWeights = parsedGeometry.matricesWeights;
  31173. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  31174. var influencers = parsedGeometry.numBoneInfluencer;
  31175. var size = matricesWeights.length;
  31176. for (var i = 0; i < size; i += 4) {
  31177. var weight = 0.0;
  31178. var firstZeroWeight = -1;
  31179. for (var j = 0; j < 4; j++) {
  31180. var w = matricesWeights[i + j];
  31181. weight += w;
  31182. if (w < epsilon && firstZeroWeight < 0) {
  31183. firstZeroWeight = j;
  31184. }
  31185. }
  31186. if (matricesWeightsExtra) {
  31187. for (var j = 0; j < 4; j++) {
  31188. var w = matricesWeightsExtra[i + j];
  31189. weight += w;
  31190. if (w < epsilon && firstZeroWeight < 0) {
  31191. firstZeroWeight = j + 4;
  31192. }
  31193. }
  31194. }
  31195. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  31196. firstZeroWeight = influencers - 1;
  31197. }
  31198. if (weight > epsilon) {
  31199. var mweight = 1.0 / weight;
  31200. for (var j = 0; j < 4; j++) {
  31201. matricesWeights[i + j] *= mweight;
  31202. }
  31203. if (matricesWeightsExtra) {
  31204. for (var j = 0; j < 4; j++) {
  31205. matricesWeightsExtra[i + j] *= mweight;
  31206. }
  31207. }
  31208. }
  31209. else {
  31210. if (firstZeroWeight >= 4) {
  31211. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  31212. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  31213. }
  31214. else {
  31215. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  31216. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  31217. }
  31218. }
  31219. }
  31220. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  31221. if (parsedGeometry.matricesWeightsExtra) {
  31222. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  31223. }
  31224. };
  31225. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  31226. if (scene.getGeometryByID(parsedVertexData.id)) {
  31227. return null; // null since geometry could be something else than a box...
  31228. }
  31229. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  31230. if (BABYLON.Tags) {
  31231. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  31232. }
  31233. if (parsedVertexData.delayLoadingFile) {
  31234. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31235. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  31236. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  31237. geometry._delayInfo = [];
  31238. if (parsedVertexData.hasUVs) {
  31239. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  31240. }
  31241. if (parsedVertexData.hasUVs2) {
  31242. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  31243. }
  31244. if (parsedVertexData.hasUVs3) {
  31245. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  31246. }
  31247. if (parsedVertexData.hasUVs4) {
  31248. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  31249. }
  31250. if (parsedVertexData.hasUVs5) {
  31251. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  31252. }
  31253. if (parsedVertexData.hasUVs6) {
  31254. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  31255. }
  31256. if (parsedVertexData.hasColors) {
  31257. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  31258. }
  31259. if (parsedVertexData.hasMatricesIndices) {
  31260. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31261. }
  31262. if (parsedVertexData.hasMatricesWeights) {
  31263. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31264. }
  31265. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  31266. }
  31267. else {
  31268. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  31269. }
  31270. scene.pushGeometry(geometry, true);
  31271. return geometry;
  31272. };
  31273. return Geometry;
  31274. }());
  31275. BABYLON.Geometry = Geometry;
  31276. /////// Primitives //////////////////////////////////////////////
  31277. (function (Geometry) {
  31278. var Primitives;
  31279. (function (Primitives) {
  31280. /// Abstract class
  31281. var _Primitive = /** @class */ (function (_super) {
  31282. __extends(_Primitive, _super);
  31283. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  31284. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  31285. if (mesh === void 0) { mesh = null; }
  31286. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  31287. _this._canBeRegenerated = _canBeRegenerated;
  31288. _this._beingRegenerated = true;
  31289. _this.regenerate();
  31290. _this._beingRegenerated = false;
  31291. return _this;
  31292. }
  31293. _Primitive.prototype.canBeRegenerated = function () {
  31294. return this._canBeRegenerated;
  31295. };
  31296. _Primitive.prototype.regenerate = function () {
  31297. if (!this._canBeRegenerated) {
  31298. return;
  31299. }
  31300. this._beingRegenerated = true;
  31301. this.setAllVerticesData(this._regenerateVertexData(), false);
  31302. this._beingRegenerated = false;
  31303. };
  31304. _Primitive.prototype.asNewGeometry = function (id) {
  31305. return _super.prototype.copy.call(this, id);
  31306. };
  31307. // overrides
  31308. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  31309. if (!this._beingRegenerated) {
  31310. return;
  31311. }
  31312. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  31313. };
  31314. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  31315. if (!this._beingRegenerated) {
  31316. return;
  31317. }
  31318. _super.prototype.setVerticesData.call(this, kind, data, false);
  31319. };
  31320. // to override
  31321. // protected
  31322. _Primitive.prototype._regenerateVertexData = function () {
  31323. throw new Error("Abstract method");
  31324. };
  31325. _Primitive.prototype.copy = function (id) {
  31326. throw new Error("Must be overriden in sub-classes.");
  31327. };
  31328. _Primitive.prototype.serialize = function () {
  31329. var serializationObject = _super.prototype.serialize.call(this);
  31330. serializationObject.canBeRegenerated = this.canBeRegenerated();
  31331. return serializationObject;
  31332. };
  31333. return _Primitive;
  31334. }(Geometry));
  31335. Primitives._Primitive = _Primitive;
  31336. var Ribbon = /** @class */ (function (_super) {
  31337. __extends(Ribbon, _super);
  31338. // Members
  31339. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  31340. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31341. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31342. _this.pathArray = pathArray;
  31343. _this.closeArray = closeArray;
  31344. _this.closePath = closePath;
  31345. _this.offset = offset;
  31346. _this.side = side;
  31347. return _this;
  31348. }
  31349. Ribbon.prototype._regenerateVertexData = function () {
  31350. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  31351. };
  31352. Ribbon.prototype.copy = function (id) {
  31353. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  31354. };
  31355. return Ribbon;
  31356. }(_Primitive));
  31357. Primitives.Ribbon = Ribbon;
  31358. var Box = /** @class */ (function (_super) {
  31359. __extends(Box, _super);
  31360. // Members
  31361. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  31362. if (mesh === void 0) { mesh = null; }
  31363. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31364. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31365. _this.size = size;
  31366. _this.side = side;
  31367. return _this;
  31368. }
  31369. Box.prototype._regenerateVertexData = function () {
  31370. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  31371. };
  31372. Box.prototype.copy = function (id) {
  31373. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  31374. };
  31375. Box.prototype.serialize = function () {
  31376. var serializationObject = _super.prototype.serialize.call(this);
  31377. serializationObject.size = this.size;
  31378. return serializationObject;
  31379. };
  31380. Box.Parse = function (parsedBox, scene) {
  31381. if (scene.getGeometryByID(parsedBox.id)) {
  31382. return null; // null since geometry could be something else than a box...
  31383. }
  31384. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  31385. if (BABYLON.Tags) {
  31386. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  31387. }
  31388. scene.pushGeometry(box, true);
  31389. return box;
  31390. };
  31391. return Box;
  31392. }(_Primitive));
  31393. Primitives.Box = Box;
  31394. var Sphere = /** @class */ (function (_super) {
  31395. __extends(Sphere, _super);
  31396. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  31397. if (mesh === void 0) { mesh = null; }
  31398. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31399. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31400. _this.segments = segments;
  31401. _this.diameter = diameter;
  31402. _this.side = side;
  31403. return _this;
  31404. }
  31405. Sphere.prototype._regenerateVertexData = function () {
  31406. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  31407. };
  31408. Sphere.prototype.copy = function (id) {
  31409. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  31410. };
  31411. Sphere.prototype.serialize = function () {
  31412. var serializationObject = _super.prototype.serialize.call(this);
  31413. serializationObject.segments = this.segments;
  31414. serializationObject.diameter = this.diameter;
  31415. return serializationObject;
  31416. };
  31417. Sphere.Parse = function (parsedSphere, scene) {
  31418. if (scene.getGeometryByID(parsedSphere.id)) {
  31419. return null; // null since geometry could be something else than a sphere...
  31420. }
  31421. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  31422. if (BABYLON.Tags) {
  31423. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  31424. }
  31425. scene.pushGeometry(sphere, true);
  31426. return sphere;
  31427. };
  31428. return Sphere;
  31429. }(_Primitive));
  31430. Primitives.Sphere = Sphere;
  31431. var Disc = /** @class */ (function (_super) {
  31432. __extends(Disc, _super);
  31433. // Members
  31434. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  31435. if (mesh === void 0) { mesh = null; }
  31436. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31437. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31438. _this.radius = radius;
  31439. _this.tessellation = tessellation;
  31440. _this.side = side;
  31441. return _this;
  31442. }
  31443. Disc.prototype._regenerateVertexData = function () {
  31444. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  31445. };
  31446. Disc.prototype.copy = function (id) {
  31447. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  31448. };
  31449. return Disc;
  31450. }(_Primitive));
  31451. Primitives.Disc = Disc;
  31452. var Cylinder = /** @class */ (function (_super) {
  31453. __extends(Cylinder, _super);
  31454. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  31455. if (subdivisions === void 0) { subdivisions = 1; }
  31456. if (mesh === void 0) { mesh = null; }
  31457. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31458. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31459. _this.height = height;
  31460. _this.diameterTop = diameterTop;
  31461. _this.diameterBottom = diameterBottom;
  31462. _this.tessellation = tessellation;
  31463. _this.subdivisions = subdivisions;
  31464. _this.side = side;
  31465. return _this;
  31466. }
  31467. Cylinder.prototype._regenerateVertexData = function () {
  31468. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  31469. };
  31470. Cylinder.prototype.copy = function (id) {
  31471. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  31472. };
  31473. Cylinder.prototype.serialize = function () {
  31474. var serializationObject = _super.prototype.serialize.call(this);
  31475. serializationObject.height = this.height;
  31476. serializationObject.diameterTop = this.diameterTop;
  31477. serializationObject.diameterBottom = this.diameterBottom;
  31478. serializationObject.tessellation = this.tessellation;
  31479. return serializationObject;
  31480. };
  31481. Cylinder.Parse = function (parsedCylinder, scene) {
  31482. if (scene.getGeometryByID(parsedCylinder.id)) {
  31483. return null; // null since geometry could be something else than a cylinder...
  31484. }
  31485. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  31486. if (BABYLON.Tags) {
  31487. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  31488. }
  31489. scene.pushGeometry(cylinder, true);
  31490. return cylinder;
  31491. };
  31492. return Cylinder;
  31493. }(_Primitive));
  31494. Primitives.Cylinder = Cylinder;
  31495. var Torus = /** @class */ (function (_super) {
  31496. __extends(Torus, _super);
  31497. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  31498. if (mesh === void 0) { mesh = null; }
  31499. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31500. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31501. _this.diameter = diameter;
  31502. _this.thickness = thickness;
  31503. _this.tessellation = tessellation;
  31504. _this.side = side;
  31505. return _this;
  31506. }
  31507. Torus.prototype._regenerateVertexData = function () {
  31508. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  31509. };
  31510. Torus.prototype.copy = function (id) {
  31511. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  31512. };
  31513. Torus.prototype.serialize = function () {
  31514. var serializationObject = _super.prototype.serialize.call(this);
  31515. serializationObject.diameter = this.diameter;
  31516. serializationObject.thickness = this.thickness;
  31517. serializationObject.tessellation = this.tessellation;
  31518. return serializationObject;
  31519. };
  31520. Torus.Parse = function (parsedTorus, scene) {
  31521. if (scene.getGeometryByID(parsedTorus.id)) {
  31522. return null; // null since geometry could be something else than a torus...
  31523. }
  31524. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  31525. if (BABYLON.Tags) {
  31526. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  31527. }
  31528. scene.pushGeometry(torus, true);
  31529. return torus;
  31530. };
  31531. return Torus;
  31532. }(_Primitive));
  31533. Primitives.Torus = Torus;
  31534. var Ground = /** @class */ (function (_super) {
  31535. __extends(Ground, _super);
  31536. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  31537. if (mesh === void 0) { mesh = null; }
  31538. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31539. _this.width = width;
  31540. _this.height = height;
  31541. _this.subdivisions = subdivisions;
  31542. return _this;
  31543. }
  31544. Ground.prototype._regenerateVertexData = function () {
  31545. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  31546. };
  31547. Ground.prototype.copy = function (id) {
  31548. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  31549. };
  31550. Ground.prototype.serialize = function () {
  31551. var serializationObject = _super.prototype.serialize.call(this);
  31552. serializationObject.width = this.width;
  31553. serializationObject.height = this.height;
  31554. serializationObject.subdivisions = this.subdivisions;
  31555. return serializationObject;
  31556. };
  31557. Ground.Parse = function (parsedGround, scene) {
  31558. if (scene.getGeometryByID(parsedGround.id)) {
  31559. return null; // null since geometry could be something else than a ground...
  31560. }
  31561. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  31562. if (BABYLON.Tags) {
  31563. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  31564. }
  31565. scene.pushGeometry(ground, true);
  31566. return ground;
  31567. };
  31568. return Ground;
  31569. }(_Primitive));
  31570. Primitives.Ground = Ground;
  31571. var TiledGround = /** @class */ (function (_super) {
  31572. __extends(TiledGround, _super);
  31573. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  31574. if (mesh === void 0) { mesh = null; }
  31575. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31576. _this.xmin = xmin;
  31577. _this.zmin = zmin;
  31578. _this.xmax = xmax;
  31579. _this.zmax = zmax;
  31580. _this.subdivisions = subdivisions;
  31581. _this.precision = precision;
  31582. return _this;
  31583. }
  31584. TiledGround.prototype._regenerateVertexData = function () {
  31585. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  31586. };
  31587. TiledGround.prototype.copy = function (id) {
  31588. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  31589. };
  31590. return TiledGround;
  31591. }(_Primitive));
  31592. Primitives.TiledGround = TiledGround;
  31593. var Plane = /** @class */ (function (_super) {
  31594. __extends(Plane, _super);
  31595. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  31596. if (mesh === void 0) { mesh = null; }
  31597. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31598. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31599. _this.size = size;
  31600. _this.side = side;
  31601. return _this;
  31602. }
  31603. Plane.prototype._regenerateVertexData = function () {
  31604. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  31605. };
  31606. Plane.prototype.copy = function (id) {
  31607. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  31608. };
  31609. Plane.prototype.serialize = function () {
  31610. var serializationObject = _super.prototype.serialize.call(this);
  31611. serializationObject.size = this.size;
  31612. return serializationObject;
  31613. };
  31614. Plane.Parse = function (parsedPlane, scene) {
  31615. if (scene.getGeometryByID(parsedPlane.id)) {
  31616. return null; // null since geometry could be something else than a ground...
  31617. }
  31618. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  31619. if (BABYLON.Tags) {
  31620. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  31621. }
  31622. scene.pushGeometry(plane, true);
  31623. return plane;
  31624. };
  31625. return Plane;
  31626. }(_Primitive));
  31627. Primitives.Plane = Plane;
  31628. var TorusKnot = /** @class */ (function (_super) {
  31629. __extends(TorusKnot, _super);
  31630. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  31631. if (mesh === void 0) { mesh = null; }
  31632. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  31633. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  31634. _this.radius = radius;
  31635. _this.tube = tube;
  31636. _this.radialSegments = radialSegments;
  31637. _this.tubularSegments = tubularSegments;
  31638. _this.p = p;
  31639. _this.q = q;
  31640. _this.side = side;
  31641. return _this;
  31642. }
  31643. TorusKnot.prototype._regenerateVertexData = function () {
  31644. 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 });
  31645. };
  31646. TorusKnot.prototype.copy = function (id) {
  31647. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  31648. };
  31649. TorusKnot.prototype.serialize = function () {
  31650. var serializationObject = _super.prototype.serialize.call(this);
  31651. serializationObject.radius = this.radius;
  31652. serializationObject.tube = this.tube;
  31653. serializationObject.radialSegments = this.radialSegments;
  31654. serializationObject.tubularSegments = this.tubularSegments;
  31655. serializationObject.p = this.p;
  31656. serializationObject.q = this.q;
  31657. return serializationObject;
  31658. };
  31659. ;
  31660. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  31661. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  31662. return null; // null since geometry could be something else than a ground...
  31663. }
  31664. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  31665. if (BABYLON.Tags) {
  31666. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  31667. }
  31668. scene.pushGeometry(torusKnot, true);
  31669. return torusKnot;
  31670. };
  31671. return TorusKnot;
  31672. }(_Primitive));
  31673. Primitives.TorusKnot = TorusKnot;
  31674. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  31675. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  31676. })(BABYLON || (BABYLON = {}));
  31677. //# sourceMappingURL=babylon.geometry.js.map
  31678. var BABYLON;
  31679. (function (BABYLON) {
  31680. var PostProcessManager = /** @class */ (function () {
  31681. function PostProcessManager(scene) {
  31682. this._vertexBuffers = {};
  31683. this._scene = scene;
  31684. }
  31685. PostProcessManager.prototype._prepareBuffers = function () {
  31686. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31687. return;
  31688. }
  31689. // VBO
  31690. var vertices = [];
  31691. vertices.push(1, 1);
  31692. vertices.push(-1, 1);
  31693. vertices.push(-1, -1);
  31694. vertices.push(1, -1);
  31695. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31696. this._buildIndexBuffer();
  31697. };
  31698. PostProcessManager.prototype._buildIndexBuffer = function () {
  31699. // Indices
  31700. var indices = [];
  31701. indices.push(0);
  31702. indices.push(1);
  31703. indices.push(2);
  31704. indices.push(0);
  31705. indices.push(2);
  31706. indices.push(3);
  31707. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31708. };
  31709. PostProcessManager.prototype._rebuild = function () {
  31710. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31711. if (!vb) {
  31712. return;
  31713. }
  31714. vb._rebuild();
  31715. this._buildIndexBuffer();
  31716. };
  31717. // Methods
  31718. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  31719. if (sourceTexture === void 0) { sourceTexture = null; }
  31720. if (postProcesses === void 0) { postProcesses = null; }
  31721. var camera = this._scene.activeCamera;
  31722. if (!camera) {
  31723. return false;
  31724. }
  31725. var postProcesses = postProcesses || camera._postProcesses;
  31726. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31727. return false;
  31728. }
  31729. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  31730. return true;
  31731. };
  31732. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  31733. if (targetTexture === void 0) { targetTexture = null; }
  31734. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31735. if (!this._scene.activeCamera) {
  31736. return;
  31737. }
  31738. var engine = this._scene.getEngine();
  31739. for (var index = 0; index < postProcesses.length; index++) {
  31740. if (index < postProcesses.length - 1) {
  31741. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31742. }
  31743. else {
  31744. if (targetTexture) {
  31745. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  31746. }
  31747. else {
  31748. engine.restoreDefaultFramebuffer();
  31749. }
  31750. }
  31751. var pp = postProcesses[index];
  31752. var effect = pp.apply();
  31753. if (effect) {
  31754. pp.onBeforeRenderObservable.notifyObservers(effect);
  31755. // VBOs
  31756. this._prepareBuffers();
  31757. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31758. // Draw order
  31759. engine.draw(true, 0, 6);
  31760. pp.onAfterRenderObservable.notifyObservers(effect);
  31761. }
  31762. }
  31763. // Restore depth buffer
  31764. engine.setDepthBuffer(true);
  31765. engine.setDepthWrite(true);
  31766. };
  31767. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  31768. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  31769. var camera = this._scene.activeCamera;
  31770. if (!camera) {
  31771. return;
  31772. }
  31773. postProcesses = postProcesses || camera._postProcesses;
  31774. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31775. return;
  31776. }
  31777. var engine = this._scene.getEngine();
  31778. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31779. if (index < len - 1) {
  31780. postProcesses[index + 1].activate(camera, targetTexture);
  31781. }
  31782. else {
  31783. if (targetTexture) {
  31784. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  31785. }
  31786. else {
  31787. engine.restoreDefaultFramebuffer();
  31788. }
  31789. }
  31790. if (doNotPresent) {
  31791. break;
  31792. }
  31793. var pp = postProcesses[index];
  31794. var effect = pp.apply();
  31795. if (effect) {
  31796. pp.onBeforeRenderObservable.notifyObservers(effect);
  31797. // VBOs
  31798. this._prepareBuffers();
  31799. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31800. // Draw order
  31801. engine.draw(true, 0, 6);
  31802. pp.onAfterRenderObservable.notifyObservers(effect);
  31803. }
  31804. }
  31805. // Restore states
  31806. engine.setDepthBuffer(true);
  31807. engine.setDepthWrite(true);
  31808. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31809. };
  31810. PostProcessManager.prototype.dispose = function () {
  31811. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31812. if (buffer) {
  31813. buffer.dispose();
  31814. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31815. }
  31816. if (this._indexBuffer) {
  31817. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31818. this._indexBuffer = null;
  31819. }
  31820. };
  31821. return PostProcessManager;
  31822. }());
  31823. BABYLON.PostProcessManager = PostProcessManager;
  31824. })(BABYLON || (BABYLON = {}));
  31825. //# sourceMappingURL=babylon.postProcessManager.js.map
  31826. var BABYLON;
  31827. (function (BABYLON) {
  31828. /**
  31829. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  31830. */
  31831. var PerformanceMonitor = /** @class */ (function () {
  31832. /**
  31833. * constructor
  31834. * @param frameSampleSize The number of samples required to saturate the sliding window
  31835. */
  31836. function PerformanceMonitor(frameSampleSize) {
  31837. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  31838. this._enabled = true;
  31839. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  31840. }
  31841. /**
  31842. * Samples current frame
  31843. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  31844. */
  31845. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  31846. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  31847. if (!this._enabled)
  31848. return;
  31849. if (this._lastFrameTimeMs != null) {
  31850. var dt = timeMs - this._lastFrameTimeMs;
  31851. this._rollingFrameTime.add(dt);
  31852. }
  31853. this._lastFrameTimeMs = timeMs;
  31854. };
  31855. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  31856. /**
  31857. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31858. * @return Average frame time in milliseconds
  31859. */
  31860. get: function () {
  31861. return this._rollingFrameTime.average;
  31862. },
  31863. enumerable: true,
  31864. configurable: true
  31865. });
  31866. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  31867. /**
  31868. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  31869. * @return Frame time variance in milliseconds squared
  31870. */
  31871. get: function () {
  31872. return this._rollingFrameTime.variance;
  31873. },
  31874. enumerable: true,
  31875. configurable: true
  31876. });
  31877. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  31878. /**
  31879. * Returns the frame time of the most recent frame
  31880. * @return Frame time in milliseconds
  31881. */
  31882. get: function () {
  31883. return this._rollingFrameTime.history(0);
  31884. },
  31885. enumerable: true,
  31886. configurable: true
  31887. });
  31888. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  31889. /**
  31890. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  31891. * @return Framerate in frames per second
  31892. */
  31893. get: function () {
  31894. return 1000.0 / this._rollingFrameTime.average;
  31895. },
  31896. enumerable: true,
  31897. configurable: true
  31898. });
  31899. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  31900. /**
  31901. * Returns the average framerate in frames per second using the most recent frame time
  31902. * @return Framerate in frames per second
  31903. */
  31904. get: function () {
  31905. var history = this._rollingFrameTime.history(0);
  31906. if (history === 0) {
  31907. return 0;
  31908. }
  31909. return 1000.0 / history;
  31910. },
  31911. enumerable: true,
  31912. configurable: true
  31913. });
  31914. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  31915. /**
  31916. * Returns true if enough samples have been taken to completely fill the sliding window
  31917. * @return true if saturated
  31918. */
  31919. get: function () {
  31920. return this._rollingFrameTime.isSaturated();
  31921. },
  31922. enumerable: true,
  31923. configurable: true
  31924. });
  31925. /**
  31926. * Enables contributions to the sliding window sample set
  31927. */
  31928. PerformanceMonitor.prototype.enable = function () {
  31929. this._enabled = true;
  31930. };
  31931. /**
  31932. * Disables contributions to the sliding window sample set
  31933. * Samples will not be interpolated over the disabled period
  31934. */
  31935. PerformanceMonitor.prototype.disable = function () {
  31936. this._enabled = false;
  31937. //clear last sample to avoid interpolating over the disabled period when next enabled
  31938. this._lastFrameTimeMs = null;
  31939. this._lastChangeTimeMs = null;
  31940. };
  31941. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  31942. /**
  31943. * Returns true if sampling is enabled
  31944. * @return true if enabled
  31945. */
  31946. get: function () {
  31947. return this._enabled;
  31948. },
  31949. enumerable: true,
  31950. configurable: true
  31951. });
  31952. /**
  31953. * Resets performance monitor
  31954. */
  31955. PerformanceMonitor.prototype.reset = function () {
  31956. //clear last sample to avoid interpolating over the disabled period when next enabled
  31957. this._lastFrameTimeMs = null;
  31958. this._lastChangeTimeMs = null;
  31959. //wipe record
  31960. this._rollingFrameTime.reset();
  31961. };
  31962. return PerformanceMonitor;
  31963. }());
  31964. BABYLON.PerformanceMonitor = PerformanceMonitor;
  31965. /**
  31966. * RollingAverage
  31967. *
  31968. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  31969. */
  31970. var RollingAverage = /** @class */ (function () {
  31971. /**
  31972. * constructor
  31973. * @param length The number of samples required to saturate the sliding window
  31974. */
  31975. function RollingAverage(length) {
  31976. this._samples = new Array(length);
  31977. this.reset();
  31978. }
  31979. /**
  31980. * Adds a sample to the sample set
  31981. * @param v The sample value
  31982. */
  31983. RollingAverage.prototype.add = function (v) {
  31984. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  31985. var delta;
  31986. //we need to check if we've already wrapped round
  31987. if (this.isSaturated()) {
  31988. //remove bottom of stack from mean
  31989. var bottomValue = this._samples[this._pos];
  31990. delta = bottomValue - this.average;
  31991. this.average -= delta / (this._sampleCount - 1);
  31992. this._m2 -= delta * (bottomValue - this.average);
  31993. }
  31994. else {
  31995. this._sampleCount++;
  31996. }
  31997. //add new value to mean
  31998. delta = v - this.average;
  31999. this.average += delta / (this._sampleCount);
  32000. this._m2 += delta * (v - this.average);
  32001. //set the new variance
  32002. this.variance = this._m2 / (this._sampleCount - 1);
  32003. this._samples[this._pos] = v;
  32004. this._pos++;
  32005. this._pos %= this._samples.length; //positive wrap around
  32006. };
  32007. /**
  32008. * Returns previously added values or null if outside of history or outside the sliding window domain
  32009. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32010. * @return Value previously recorded with add() or null if outside of range
  32011. */
  32012. RollingAverage.prototype.history = function (i) {
  32013. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32014. return 0;
  32015. }
  32016. var i0 = this._wrapPosition(this._pos - 1.0);
  32017. return this._samples[this._wrapPosition(i0 - i)];
  32018. };
  32019. /**
  32020. * Returns true if enough samples have been taken to completely fill the sliding window
  32021. * @return true if sample-set saturated
  32022. */
  32023. RollingAverage.prototype.isSaturated = function () {
  32024. return this._sampleCount >= this._samples.length;
  32025. };
  32026. /**
  32027. * Resets the rolling average (equivalent to 0 samples taken so far)
  32028. */
  32029. RollingAverage.prototype.reset = function () {
  32030. this.average = 0;
  32031. this.variance = 0;
  32032. this._sampleCount = 0;
  32033. this._pos = 0;
  32034. this._m2 = 0;
  32035. };
  32036. /**
  32037. * Wraps a value around the sample range boundaries
  32038. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32039. * @return Wrapped position in sample range
  32040. */
  32041. RollingAverage.prototype._wrapPosition = function (i) {
  32042. var max = this._samples.length;
  32043. return ((i % max) + max) % max;
  32044. };
  32045. return RollingAverage;
  32046. }());
  32047. BABYLON.RollingAverage = RollingAverage;
  32048. })(BABYLON || (BABYLON = {}));
  32049. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32050. var BABYLON;
  32051. (function (BABYLON) {
  32052. /**
  32053. * This groups together the common properties used for image processing either in direct forward pass
  32054. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32055. * or not.
  32056. */
  32057. var ImageProcessingConfiguration = /** @class */ (function () {
  32058. function ImageProcessingConfiguration() {
  32059. /**
  32060. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32061. */
  32062. this.colorCurves = new BABYLON.ColorCurves();
  32063. this._colorCurvesEnabled = false;
  32064. this._colorGradingEnabled = false;
  32065. this._colorGradingWithGreenDepth = true;
  32066. this._colorGradingBGR = true;
  32067. this._exposure = 1.0;
  32068. this._toneMappingEnabled = false;
  32069. this._contrast = 1.0;
  32070. /**
  32071. * Vignette stretch size.
  32072. */
  32073. this.vignetteStretch = 0;
  32074. /**
  32075. * Vignette centre X Offset.
  32076. */
  32077. this.vignetteCentreX = 0;
  32078. /**
  32079. * Vignette centre Y Offset.
  32080. */
  32081. this.vignetteCentreY = 0;
  32082. /**
  32083. * Vignette weight or intensity of the vignette effect.
  32084. */
  32085. this.vignetteWeight = 1.5;
  32086. /**
  32087. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32088. * if vignetteEnabled is set to true.
  32089. */
  32090. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32091. /**
  32092. * Camera field of view used by the Vignette effect.
  32093. */
  32094. this.vignetteCameraFov = 0.5;
  32095. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32096. this._vignetteEnabled = false;
  32097. this._applyByPostProcess = false;
  32098. /**
  32099. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32100. * @type {BABYLON.Observable}
  32101. */
  32102. this.onUpdateParameters = new BABYLON.Observable();
  32103. }
  32104. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32105. /**
  32106. * Gets wether the color curves effect is enabled.
  32107. */
  32108. get: function () {
  32109. return this._colorCurvesEnabled;
  32110. },
  32111. /**
  32112. * Sets wether the color curves effect is enabled.
  32113. */
  32114. set: function (value) {
  32115. if (this._colorCurvesEnabled === value) {
  32116. return;
  32117. }
  32118. this._colorCurvesEnabled = value;
  32119. this._updateParameters();
  32120. },
  32121. enumerable: true,
  32122. configurable: true
  32123. });
  32124. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32125. /**
  32126. * Gets wether the color grading effect is enabled.
  32127. */
  32128. get: function () {
  32129. return this._colorGradingEnabled;
  32130. },
  32131. /**
  32132. * Sets wether the color grading effect is enabled.
  32133. */
  32134. set: function (value) {
  32135. if (this._colorGradingEnabled === value) {
  32136. return;
  32137. }
  32138. this._colorGradingEnabled = value;
  32139. this._updateParameters();
  32140. },
  32141. enumerable: true,
  32142. configurable: true
  32143. });
  32144. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32145. /**
  32146. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32147. */
  32148. get: function () {
  32149. return this._colorGradingWithGreenDepth;
  32150. },
  32151. /**
  32152. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32153. */
  32154. set: function (value) {
  32155. if (this._colorGradingWithGreenDepth === value) {
  32156. return;
  32157. }
  32158. this._colorGradingWithGreenDepth = value;
  32159. this._updateParameters();
  32160. },
  32161. enumerable: true,
  32162. configurable: true
  32163. });
  32164. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  32165. /**
  32166. * Gets wether the color grading texture contains BGR values.
  32167. */
  32168. get: function () {
  32169. return this._colorGradingBGR;
  32170. },
  32171. /**
  32172. * Sets wether the color grading texture contains BGR values.
  32173. */
  32174. set: function (value) {
  32175. if (this._colorGradingBGR === value) {
  32176. return;
  32177. }
  32178. this._colorGradingBGR = value;
  32179. this._updateParameters();
  32180. },
  32181. enumerable: true,
  32182. configurable: true
  32183. });
  32184. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  32185. /**
  32186. * Gets the Exposure used in the effect.
  32187. */
  32188. get: function () {
  32189. return this._exposure;
  32190. },
  32191. /**
  32192. * Sets the Exposure used in the effect.
  32193. */
  32194. set: function (value) {
  32195. if (this._exposure === value) {
  32196. return;
  32197. }
  32198. this._exposure = value;
  32199. this._updateParameters();
  32200. },
  32201. enumerable: true,
  32202. configurable: true
  32203. });
  32204. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  32205. /**
  32206. * Gets wether the tone mapping effect is enabled.
  32207. */
  32208. get: function () {
  32209. return this._toneMappingEnabled;
  32210. },
  32211. /**
  32212. * Sets wether the tone mapping effect is enabled.
  32213. */
  32214. set: function (value) {
  32215. if (this._toneMappingEnabled === value) {
  32216. return;
  32217. }
  32218. this._toneMappingEnabled = value;
  32219. this._updateParameters();
  32220. },
  32221. enumerable: true,
  32222. configurable: true
  32223. });
  32224. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  32225. /**
  32226. * Gets the contrast used in the effect.
  32227. */
  32228. get: function () {
  32229. return this._contrast;
  32230. },
  32231. /**
  32232. * Sets the contrast used in the effect.
  32233. */
  32234. set: function (value) {
  32235. if (this._contrast === value) {
  32236. return;
  32237. }
  32238. this._contrast = value;
  32239. this._updateParameters();
  32240. },
  32241. enumerable: true,
  32242. configurable: true
  32243. });
  32244. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  32245. /**
  32246. * Gets the vignette blend mode allowing different kind of effect.
  32247. */
  32248. get: function () {
  32249. return this._vignetteBlendMode;
  32250. },
  32251. /**
  32252. * Sets the vignette blend mode allowing different kind of effect.
  32253. */
  32254. set: function (value) {
  32255. if (this._vignetteBlendMode === value) {
  32256. return;
  32257. }
  32258. this._vignetteBlendMode = value;
  32259. this._updateParameters();
  32260. },
  32261. enumerable: true,
  32262. configurable: true
  32263. });
  32264. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  32265. /**
  32266. * Gets wether the vignette effect is enabled.
  32267. */
  32268. get: function () {
  32269. return this._vignetteEnabled;
  32270. },
  32271. /**
  32272. * Sets wether the vignette effect is enabled.
  32273. */
  32274. set: function (value) {
  32275. if (this._vignetteEnabled === value) {
  32276. return;
  32277. }
  32278. this._vignetteEnabled = value;
  32279. this._updateParameters();
  32280. },
  32281. enumerable: true,
  32282. configurable: true
  32283. });
  32284. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  32285. /**
  32286. * Gets wether the image processing is applied through a post process or not.
  32287. */
  32288. get: function () {
  32289. return this._applyByPostProcess;
  32290. },
  32291. /**
  32292. * Sets wether the image processing is applied through a post process or not.
  32293. */
  32294. set: function (value) {
  32295. if (this._applyByPostProcess === value) {
  32296. return;
  32297. }
  32298. this._applyByPostProcess = value;
  32299. this._updateParameters();
  32300. },
  32301. enumerable: true,
  32302. configurable: true
  32303. });
  32304. /**
  32305. * Method called each time the image processing information changes requires to recompile the effect.
  32306. */
  32307. ImageProcessingConfiguration.prototype._updateParameters = function () {
  32308. this.onUpdateParameters.notifyObservers(this);
  32309. };
  32310. ImageProcessingConfiguration.prototype.getClassName = function () {
  32311. return "ImageProcessingConfiguration";
  32312. };
  32313. /**
  32314. * Prepare the list of uniforms associated with the Image Processing effects.
  32315. * @param uniformsList The list of uniforms used in the effect
  32316. * @param defines the list of defines currently in use
  32317. */
  32318. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  32319. if (defines.EXPOSURE) {
  32320. uniforms.push("exposureLinear");
  32321. }
  32322. if (defines.CONTRAST) {
  32323. uniforms.push("contrast");
  32324. }
  32325. if (defines.COLORGRADING) {
  32326. uniforms.push("colorTransformSettings");
  32327. }
  32328. if (defines.VIGNETTE) {
  32329. uniforms.push("vInverseScreenSize");
  32330. uniforms.push("vignetteSettings1");
  32331. uniforms.push("vignetteSettings2");
  32332. }
  32333. if (defines.COLORCURVES) {
  32334. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  32335. }
  32336. };
  32337. /**
  32338. * Prepare the list of samplers associated with the Image Processing effects.
  32339. * @param uniformsList The list of uniforms used in the effect
  32340. * @param defines the list of defines currently in use
  32341. */
  32342. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  32343. if (defines.COLORGRADING) {
  32344. samplersList.push("txColorTransform");
  32345. }
  32346. };
  32347. /**
  32348. * Prepare the list of defines associated to the shader.
  32349. * @param defines the list of defines to complete
  32350. */
  32351. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  32352. if (forPostProcess === void 0) { forPostProcess = false; }
  32353. if (forPostProcess !== this.applyByPostProcess) {
  32354. defines.VIGNETTE = false;
  32355. defines.TONEMAPPING = false;
  32356. defines.CONTRAST = false;
  32357. defines.EXPOSURE = false;
  32358. defines.COLORCURVES = false;
  32359. defines.COLORGRADING = false;
  32360. defines.COLORGRADING3D = false;
  32361. defines.IMAGEPROCESSING = false;
  32362. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32363. return;
  32364. }
  32365. defines.VIGNETTE = this.vignetteEnabled;
  32366. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  32367. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  32368. defines.TONEMAPPING = this.toneMappingEnabled;
  32369. defines.CONTRAST = (this.contrast !== 1.0);
  32370. defines.EXPOSURE = (this.exposure !== 1.0);
  32371. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  32372. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  32373. if (defines.COLORGRADING) {
  32374. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  32375. }
  32376. else {
  32377. defines.COLORGRADING3D = false;
  32378. }
  32379. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  32380. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  32381. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  32382. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  32383. };
  32384. /**
  32385. * Returns true if all the image processing information are ready.
  32386. */
  32387. ImageProcessingConfiguration.prototype.isReady = function () {
  32388. // Color Grading texure can not be none blocking.
  32389. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  32390. };
  32391. /**
  32392. * Binds the image processing to the shader.
  32393. * @param effect The effect to bind to
  32394. */
  32395. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  32396. if (aspectRatio === void 0) { aspectRatio = 1; }
  32397. // Color Curves
  32398. if (this._colorCurvesEnabled && this.colorCurves) {
  32399. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  32400. }
  32401. // Vignette
  32402. if (this._vignetteEnabled) {
  32403. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  32404. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  32405. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  32406. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  32407. var vignetteScaleX = vignetteScaleY * aspectRatio;
  32408. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  32409. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  32410. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  32411. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  32412. var vignettePower = -2.0 * this.vignetteWeight;
  32413. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  32414. }
  32415. // Exposure
  32416. effect.setFloat("exposureLinear", this.exposure);
  32417. // Contrast
  32418. effect.setFloat("contrast", this.contrast);
  32419. // Color transform settings
  32420. if (this.colorGradingTexture) {
  32421. effect.setTexture("txColorTransform", this.colorGradingTexture);
  32422. var textureSize = this.colorGradingTexture.getSize().height;
  32423. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  32424. 0.5 / textureSize, // textureOffset
  32425. textureSize, // textureSize
  32426. this.colorGradingTexture.level // weight
  32427. );
  32428. }
  32429. };
  32430. /**
  32431. * Clones the current image processing instance.
  32432. * @return The cloned image processing
  32433. */
  32434. ImageProcessingConfiguration.prototype.clone = function () {
  32435. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  32436. };
  32437. /**
  32438. * Serializes the current image processing instance to a json representation.
  32439. * @return a JSON representation
  32440. */
  32441. ImageProcessingConfiguration.prototype.serialize = function () {
  32442. return BABYLON.SerializationHelper.Serialize(this);
  32443. };
  32444. /**
  32445. * Parses the image processing from a json representation.
  32446. * @param source the JSON source to parse
  32447. * @return The parsed image processing
  32448. */
  32449. ImageProcessingConfiguration.Parse = function (source) {
  32450. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  32451. };
  32452. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  32453. /**
  32454. * Used to apply the vignette as a mix with the pixel color.
  32455. */
  32456. get: function () {
  32457. return this._VIGNETTEMODE_MULTIPLY;
  32458. },
  32459. enumerable: true,
  32460. configurable: true
  32461. });
  32462. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  32463. /**
  32464. * Used to apply the vignette as a replacement of the pixel color.
  32465. */
  32466. get: function () {
  32467. return this._VIGNETTEMODE_OPAQUE;
  32468. },
  32469. enumerable: true,
  32470. configurable: true
  32471. });
  32472. // Static constants associated to the image processing.
  32473. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  32474. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  32475. __decorate([
  32476. BABYLON.serializeAsColorCurves()
  32477. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  32478. __decorate([
  32479. BABYLON.serialize()
  32480. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  32481. __decorate([
  32482. BABYLON.serializeAsTexture()
  32483. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  32484. __decorate([
  32485. BABYLON.serialize()
  32486. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  32487. __decorate([
  32488. BABYLON.serialize()
  32489. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  32490. __decorate([
  32491. BABYLON.serialize()
  32492. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  32493. __decorate([
  32494. BABYLON.serialize()
  32495. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  32496. __decorate([
  32497. BABYLON.serialize()
  32498. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  32499. __decorate([
  32500. BABYLON.serialize()
  32501. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  32502. __decorate([
  32503. BABYLON.serialize()
  32504. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  32505. __decorate([
  32506. BABYLON.serialize()
  32507. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  32508. __decorate([
  32509. BABYLON.serialize()
  32510. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  32511. __decorate([
  32512. BABYLON.serialize()
  32513. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  32514. __decorate([
  32515. BABYLON.serializeAsColor4()
  32516. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  32517. __decorate([
  32518. BABYLON.serialize()
  32519. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  32520. __decorate([
  32521. BABYLON.serialize()
  32522. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  32523. __decorate([
  32524. BABYLON.serialize()
  32525. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  32526. __decorate([
  32527. BABYLON.serialize()
  32528. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  32529. return ImageProcessingConfiguration;
  32530. }());
  32531. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  32532. })(BABYLON || (BABYLON = {}));
  32533. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  32534. var BABYLON;
  32535. (function (BABYLON) {
  32536. /**
  32537. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  32538. * It can help converting any input color in a desired output one. This can then be used to create effects
  32539. * from sepia, black and white to sixties or futuristic rendering...
  32540. *
  32541. * The only supported format is currently 3dl.
  32542. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  32543. */
  32544. var ColorGradingTexture = /** @class */ (function (_super) {
  32545. __extends(ColorGradingTexture, _super);
  32546. /**
  32547. * Instantiates a ColorGradingTexture from the following parameters.
  32548. *
  32549. * @param url The location of the color gradind data (currently only supporting 3dl)
  32550. * @param scene The scene the texture will be used in
  32551. */
  32552. function ColorGradingTexture(url, scene) {
  32553. var _this = _super.call(this, scene) || this;
  32554. if (!url) {
  32555. return _this;
  32556. }
  32557. _this._engine = scene.getEngine();
  32558. _this._textureMatrix = BABYLON.Matrix.Identity();
  32559. _this.name = url;
  32560. _this.url = url;
  32561. _this.hasAlpha = false;
  32562. _this.isCube = false;
  32563. _this.is3D = _this._engine.webGLVersion > 1;
  32564. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32565. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32566. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  32567. _this.anisotropicFilteringLevel = 1;
  32568. _this._texture = _this._getFromCache(url, true);
  32569. if (!_this._texture) {
  32570. if (!scene.useDelayedTextureLoading) {
  32571. _this.loadTexture();
  32572. }
  32573. else {
  32574. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32575. }
  32576. }
  32577. return _this;
  32578. }
  32579. /**
  32580. * Returns the texture matrix used in most of the material.
  32581. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  32582. */
  32583. ColorGradingTexture.prototype.getTextureMatrix = function () {
  32584. return this._textureMatrix;
  32585. };
  32586. /**
  32587. * Occurs when the file being loaded is a .3dl LUT file.
  32588. */
  32589. ColorGradingTexture.prototype.load3dlTexture = function () {
  32590. var engine = this._engine;
  32591. var texture;
  32592. if (engine.webGLVersion === 1) {
  32593. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32594. }
  32595. else {
  32596. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  32597. }
  32598. this._texture = texture;
  32599. var callback = function (text) {
  32600. var data = null;
  32601. var tempData = null;
  32602. var line;
  32603. var lines = text.split('\n');
  32604. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  32605. var maxColor = 0;
  32606. for (var i = 0; i < lines.length; i++) {
  32607. line = lines[i];
  32608. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  32609. continue;
  32610. if (line.indexOf('#') === 0)
  32611. continue;
  32612. var words = line.split(" ");
  32613. if (size === 0) {
  32614. // Number of space + one
  32615. size = words.length;
  32616. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  32617. tempData = new Float32Array(size * size * size * 4);
  32618. continue;
  32619. }
  32620. if (size != 0) {
  32621. var r = Math.max(parseInt(words[0]), 0);
  32622. var g = Math.max(parseInt(words[1]), 0);
  32623. var b = Math.max(parseInt(words[2]), 0);
  32624. maxColor = Math.max(r, maxColor);
  32625. maxColor = Math.max(g, maxColor);
  32626. maxColor = Math.max(b, maxColor);
  32627. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  32628. if (tempData) {
  32629. tempData[pixelStorageIndex + 0] = r;
  32630. tempData[pixelStorageIndex + 1] = g;
  32631. tempData[pixelStorageIndex + 2] = b;
  32632. }
  32633. pixelIndexSlice++;
  32634. if (pixelIndexSlice % size == 0) {
  32635. pixelIndexH++;
  32636. pixelIndexSlice = 0;
  32637. if (pixelIndexH % size == 0) {
  32638. pixelIndexW++;
  32639. pixelIndexH = 0;
  32640. }
  32641. }
  32642. }
  32643. }
  32644. if (tempData && data) {
  32645. for (var i = 0; i < tempData.length; i++) {
  32646. if (i > 0 && (i + 1) % 4 === 0) {
  32647. data[i] = 255;
  32648. }
  32649. else {
  32650. var value = tempData[i];
  32651. data[i] = (value / maxColor * 255);
  32652. }
  32653. }
  32654. }
  32655. if (texture.is3D) {
  32656. texture.updateSize(size, size, size);
  32657. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32658. }
  32659. else {
  32660. texture.updateSize(size * size, size);
  32661. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  32662. }
  32663. };
  32664. BABYLON.Tools.LoadFile(this.url, callback);
  32665. return this._texture;
  32666. };
  32667. /**
  32668. * Starts the loading process of the texture.
  32669. */
  32670. ColorGradingTexture.prototype.loadTexture = function () {
  32671. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  32672. this.load3dlTexture();
  32673. }
  32674. };
  32675. /**
  32676. * Clones the color gradind texture.
  32677. */
  32678. ColorGradingTexture.prototype.clone = function () {
  32679. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  32680. // Base texture
  32681. newTexture.level = this.level;
  32682. return newTexture;
  32683. };
  32684. /**
  32685. * Called during delayed load for textures.
  32686. */
  32687. ColorGradingTexture.prototype.delayLoad = function () {
  32688. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32689. return;
  32690. }
  32691. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32692. this._texture = this._getFromCache(this.url, true);
  32693. if (!this._texture) {
  32694. this.loadTexture();
  32695. }
  32696. };
  32697. /**
  32698. * Parses a color grading texture serialized by Babylon.
  32699. * @param parsedTexture The texture information being parsedTexture
  32700. * @param scene The scene to load the texture in
  32701. * @param rootUrl The root url of the data assets to load
  32702. * @return A color gradind texture
  32703. */
  32704. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  32705. var texture = null;
  32706. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  32707. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  32708. texture.name = parsedTexture.name;
  32709. texture.level = parsedTexture.level;
  32710. }
  32711. return texture;
  32712. };
  32713. /**
  32714. * Serializes the LUT texture to json format.
  32715. */
  32716. ColorGradingTexture.prototype.serialize = function () {
  32717. if (!this.name) {
  32718. return null;
  32719. }
  32720. var serializationObject = {};
  32721. serializationObject.name = this.name;
  32722. serializationObject.level = this.level;
  32723. serializationObject.customType = "BABYLON.ColorGradingTexture";
  32724. return serializationObject;
  32725. };
  32726. /**
  32727. * Empty line regex stored for GC.
  32728. */
  32729. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  32730. return ColorGradingTexture;
  32731. }(BABYLON.BaseTexture));
  32732. BABYLON.ColorGradingTexture = ColorGradingTexture;
  32733. })(BABYLON || (BABYLON = {}));
  32734. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  32735. var BABYLON;
  32736. (function (BABYLON) {
  32737. /**
  32738. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  32739. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  32740. * 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;
  32741. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  32742. */
  32743. var ColorCurves = /** @class */ (function () {
  32744. function ColorCurves() {
  32745. this._dirty = true;
  32746. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  32747. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  32748. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32749. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  32750. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  32751. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  32752. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  32753. this._globalHue = 30;
  32754. this._globalDensity = 0;
  32755. this._globalSaturation = 0;
  32756. this._globalExposure = 0;
  32757. this._highlightsHue = 30;
  32758. this._highlightsDensity = 0;
  32759. this._highlightsSaturation = 0;
  32760. this._highlightsExposure = 0;
  32761. this._midtonesHue = 30;
  32762. this._midtonesDensity = 0;
  32763. this._midtonesSaturation = 0;
  32764. this._midtonesExposure = 0;
  32765. this._shadowsHue = 30;
  32766. this._shadowsDensity = 0;
  32767. this._shadowsSaturation = 0;
  32768. this._shadowsExposure = 0;
  32769. }
  32770. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  32771. /**
  32772. * Gets the global Hue value.
  32773. * 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).
  32774. */
  32775. get: function () {
  32776. return this._globalHue;
  32777. },
  32778. /**
  32779. * Sets the global Hue value.
  32780. * 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).
  32781. */
  32782. set: function (value) {
  32783. this._globalHue = value;
  32784. this._dirty = true;
  32785. },
  32786. enumerable: true,
  32787. configurable: true
  32788. });
  32789. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  32790. /**
  32791. * Gets the global Density value.
  32792. * 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.
  32793. * Values less than zero provide a filter of opposite hue.
  32794. */
  32795. get: function () {
  32796. return this._globalDensity;
  32797. },
  32798. /**
  32799. * Sets the global Density value.
  32800. * 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.
  32801. * Values less than zero provide a filter of opposite hue.
  32802. */
  32803. set: function (value) {
  32804. this._globalDensity = value;
  32805. this._dirty = true;
  32806. },
  32807. enumerable: true,
  32808. configurable: true
  32809. });
  32810. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  32811. /**
  32812. * Gets the global Saturation value.
  32813. * 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.
  32814. */
  32815. get: function () {
  32816. return this._globalSaturation;
  32817. },
  32818. /**
  32819. * Sets the global Saturation value.
  32820. * 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.
  32821. */
  32822. set: function (value) {
  32823. this._globalSaturation = value;
  32824. this._dirty = true;
  32825. },
  32826. enumerable: true,
  32827. configurable: true
  32828. });
  32829. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  32830. /**
  32831. * Gets the highlights Hue value.
  32832. * 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).
  32833. */
  32834. get: function () {
  32835. return this._highlightsHue;
  32836. },
  32837. /**
  32838. * Sets the highlights Hue value.
  32839. * 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).
  32840. */
  32841. set: function (value) {
  32842. this._highlightsHue = value;
  32843. this._dirty = true;
  32844. },
  32845. enumerable: true,
  32846. configurable: true
  32847. });
  32848. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  32849. /**
  32850. * Gets the highlights Density value.
  32851. * 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.
  32852. * Values less than zero provide a filter of opposite hue.
  32853. */
  32854. get: function () {
  32855. return this._highlightsDensity;
  32856. },
  32857. /**
  32858. * Sets the highlights Density value.
  32859. * 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.
  32860. * Values less than zero provide a filter of opposite hue.
  32861. */
  32862. set: function (value) {
  32863. this._highlightsDensity = value;
  32864. this._dirty = true;
  32865. },
  32866. enumerable: true,
  32867. configurable: true
  32868. });
  32869. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  32870. /**
  32871. * Gets the highlights Saturation value.
  32872. * 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.
  32873. */
  32874. get: function () {
  32875. return this._highlightsSaturation;
  32876. },
  32877. /**
  32878. * Sets the highlights Saturation value.
  32879. * 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.
  32880. */
  32881. set: function (value) {
  32882. this._highlightsSaturation = value;
  32883. this._dirty = true;
  32884. },
  32885. enumerable: true,
  32886. configurable: true
  32887. });
  32888. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  32889. /**
  32890. * Gets the highlights Exposure value.
  32891. * 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.
  32892. */
  32893. get: function () {
  32894. return this._highlightsExposure;
  32895. },
  32896. /**
  32897. * Sets the highlights Exposure value.
  32898. * 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.
  32899. */
  32900. set: function (value) {
  32901. this._highlightsExposure = value;
  32902. this._dirty = true;
  32903. },
  32904. enumerable: true,
  32905. configurable: true
  32906. });
  32907. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  32908. /**
  32909. * Gets the midtones Hue value.
  32910. * 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).
  32911. */
  32912. get: function () {
  32913. return this._midtonesHue;
  32914. },
  32915. /**
  32916. * Sets the midtones Hue value.
  32917. * 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).
  32918. */
  32919. set: function (value) {
  32920. this._midtonesHue = value;
  32921. this._dirty = true;
  32922. },
  32923. enumerable: true,
  32924. configurable: true
  32925. });
  32926. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  32927. /**
  32928. * Gets the midtones Density value.
  32929. * 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.
  32930. * Values less than zero provide a filter of opposite hue.
  32931. */
  32932. get: function () {
  32933. return this._midtonesDensity;
  32934. },
  32935. /**
  32936. * Sets the midtones Density value.
  32937. * 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.
  32938. * Values less than zero provide a filter of opposite hue.
  32939. */
  32940. set: function (value) {
  32941. this._midtonesDensity = value;
  32942. this._dirty = true;
  32943. },
  32944. enumerable: true,
  32945. configurable: true
  32946. });
  32947. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  32948. /**
  32949. * Gets the midtones Saturation value.
  32950. * 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.
  32951. */
  32952. get: function () {
  32953. return this._midtonesSaturation;
  32954. },
  32955. /**
  32956. * Sets the midtones Saturation value.
  32957. * 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.
  32958. */
  32959. set: function (value) {
  32960. this._midtonesSaturation = value;
  32961. this._dirty = true;
  32962. },
  32963. enumerable: true,
  32964. configurable: true
  32965. });
  32966. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  32967. /**
  32968. * Gets the midtones Exposure value.
  32969. * 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.
  32970. */
  32971. get: function () {
  32972. return this._midtonesExposure;
  32973. },
  32974. /**
  32975. * Sets the midtones Exposure value.
  32976. * 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.
  32977. */
  32978. set: function (value) {
  32979. this._midtonesExposure = value;
  32980. this._dirty = true;
  32981. },
  32982. enumerable: true,
  32983. configurable: true
  32984. });
  32985. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  32986. /**
  32987. * Gets the shadows Hue value.
  32988. * 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).
  32989. */
  32990. get: function () {
  32991. return this._shadowsHue;
  32992. },
  32993. /**
  32994. * Sets the shadows Hue value.
  32995. * 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).
  32996. */
  32997. set: function (value) {
  32998. this._shadowsHue = value;
  32999. this._dirty = true;
  33000. },
  33001. enumerable: true,
  33002. configurable: true
  33003. });
  33004. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33005. /**
  33006. * Gets the shadows Density value.
  33007. * 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.
  33008. * Values less than zero provide a filter of opposite hue.
  33009. */
  33010. get: function () {
  33011. return this._shadowsDensity;
  33012. },
  33013. /**
  33014. * Sets the shadows Density value.
  33015. * 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.
  33016. * Values less than zero provide a filter of opposite hue.
  33017. */
  33018. set: function (value) {
  33019. this._shadowsDensity = value;
  33020. this._dirty = true;
  33021. },
  33022. enumerable: true,
  33023. configurable: true
  33024. });
  33025. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33026. /**
  33027. * Gets the shadows Saturation value.
  33028. * 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.
  33029. */
  33030. get: function () {
  33031. return this._shadowsSaturation;
  33032. },
  33033. /**
  33034. * Sets the shadows Saturation value.
  33035. * 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.
  33036. */
  33037. set: function (value) {
  33038. this._shadowsSaturation = value;
  33039. this._dirty = true;
  33040. },
  33041. enumerable: true,
  33042. configurable: true
  33043. });
  33044. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33045. /**
  33046. * Gets the shadows Exposure value.
  33047. * 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.
  33048. */
  33049. get: function () {
  33050. return this._shadowsExposure;
  33051. },
  33052. /**
  33053. * Sets the shadows Exposure value.
  33054. * 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.
  33055. */
  33056. set: function (value) {
  33057. this._shadowsExposure = value;
  33058. this._dirty = true;
  33059. },
  33060. enumerable: true,
  33061. configurable: true
  33062. });
  33063. ColorCurves.prototype.getClassName = function () {
  33064. return "ColorCurves";
  33065. };
  33066. /**
  33067. * Binds the color curves to the shader.
  33068. * @param colorCurves The color curve to bind
  33069. * @param effect The effect to bind to
  33070. */
  33071. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33072. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33073. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33074. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33075. if (colorCurves._dirty) {
  33076. colorCurves._dirty = false;
  33077. // Fill in global info.
  33078. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33079. // Compute highlights info.
  33080. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33081. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33082. // Compute midtones info.
  33083. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33084. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33085. // Compute shadows info.
  33086. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33087. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33088. // Compute deltas (neutral is midtones).
  33089. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33090. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33091. }
  33092. if (effect) {
  33093. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33094. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33095. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33096. }
  33097. };
  33098. /**
  33099. * Prepare the list of uniforms associated with the ColorCurves effects.
  33100. * @param uniformsList The list of uniforms used in the effect
  33101. */
  33102. ColorCurves.PrepareUniforms = function (uniformsList) {
  33103. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33104. };
  33105. /**
  33106. * Returns color grading data based on a hue, density, saturation and exposure value.
  33107. * @param filterHue The hue of the color filter.
  33108. * @param filterDensity The density of the color filter.
  33109. * @param saturation The saturation.
  33110. * @param exposure The exposure.
  33111. * @param result The result data container.
  33112. */
  33113. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33114. if (hue == null) {
  33115. return;
  33116. }
  33117. hue = ColorCurves.clamp(hue, 0, 360);
  33118. density = ColorCurves.clamp(density, -100, 100);
  33119. saturation = ColorCurves.clamp(saturation, -100, 100);
  33120. exposure = ColorCurves.clamp(exposure, -100, 100);
  33121. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33122. // so that the maximum filter density is only 50% control. This provides fine control
  33123. // for small values and reasonable range.
  33124. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  33125. density *= 0.5;
  33126. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  33127. if (density < 0) {
  33128. density *= -1;
  33129. hue = (hue + 180) % 360;
  33130. }
  33131. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  33132. result.scaleToRef(2, result);
  33133. result.a = 1 + 0.01 * saturation;
  33134. };
  33135. /**
  33136. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  33137. * @param value The input slider value in range [-100,100].
  33138. * @returns Adjusted value.
  33139. */
  33140. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  33141. value /= 100;
  33142. var x = Math.abs(value);
  33143. x = Math.pow(x, 2);
  33144. if (value < 0) {
  33145. x *= -1;
  33146. }
  33147. x *= 100;
  33148. return x;
  33149. };
  33150. /**
  33151. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  33152. * @param hue The hue (H) input.
  33153. * @param saturation The saturation (S) input.
  33154. * @param brightness The brightness (B) input.
  33155. * @result An RGBA color represented as Vector4.
  33156. */
  33157. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  33158. var h = ColorCurves.clamp(hue, 0, 360);
  33159. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  33160. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  33161. if (s === 0) {
  33162. result.r = v;
  33163. result.g = v;
  33164. result.b = v;
  33165. }
  33166. else {
  33167. // sector 0 to 5
  33168. h /= 60;
  33169. var i = Math.floor(h);
  33170. // fractional part of h
  33171. var f = h - i;
  33172. var p = v * (1 - s);
  33173. var q = v * (1 - s * f);
  33174. var t = v * (1 - s * (1 - f));
  33175. switch (i) {
  33176. case 0:
  33177. result.r = v;
  33178. result.g = t;
  33179. result.b = p;
  33180. break;
  33181. case 1:
  33182. result.r = q;
  33183. result.g = v;
  33184. result.b = p;
  33185. break;
  33186. case 2:
  33187. result.r = p;
  33188. result.g = v;
  33189. result.b = t;
  33190. break;
  33191. case 3:
  33192. result.r = p;
  33193. result.g = q;
  33194. result.b = v;
  33195. break;
  33196. case 4:
  33197. result.r = t;
  33198. result.g = p;
  33199. result.b = v;
  33200. break;
  33201. default:// case 5:
  33202. result.r = v;
  33203. result.g = p;
  33204. result.b = q;
  33205. break;
  33206. }
  33207. }
  33208. result.a = 1;
  33209. };
  33210. /**
  33211. * Returns a value clamped between min and max
  33212. * @param value The value to clamp
  33213. * @param min The minimum of value
  33214. * @param max The maximum of value
  33215. * @returns The clamped value.
  33216. */
  33217. ColorCurves.clamp = function (value, min, max) {
  33218. return Math.min(Math.max(value, min), max);
  33219. };
  33220. /**
  33221. * Clones the current color curve instance.
  33222. * @return The cloned curves
  33223. */
  33224. ColorCurves.prototype.clone = function () {
  33225. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  33226. };
  33227. /**
  33228. * Serializes the current color curve instance to a json representation.
  33229. * @return a JSON representation
  33230. */
  33231. ColorCurves.prototype.serialize = function () {
  33232. return BABYLON.SerializationHelper.Serialize(this);
  33233. };
  33234. /**
  33235. * Parses the color curve from a json representation.
  33236. * @param source the JSON source to parse
  33237. * @return The parsed curves
  33238. */
  33239. ColorCurves.Parse = function (source) {
  33240. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  33241. };
  33242. __decorate([
  33243. BABYLON.serialize()
  33244. ], ColorCurves.prototype, "_globalHue", void 0);
  33245. __decorate([
  33246. BABYLON.serialize()
  33247. ], ColorCurves.prototype, "_globalDensity", void 0);
  33248. __decorate([
  33249. BABYLON.serialize()
  33250. ], ColorCurves.prototype, "_globalSaturation", void 0);
  33251. __decorate([
  33252. BABYLON.serialize()
  33253. ], ColorCurves.prototype, "_globalExposure", void 0);
  33254. __decorate([
  33255. BABYLON.serialize()
  33256. ], ColorCurves.prototype, "_highlightsHue", void 0);
  33257. __decorate([
  33258. BABYLON.serialize()
  33259. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  33260. __decorate([
  33261. BABYLON.serialize()
  33262. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  33263. __decorate([
  33264. BABYLON.serialize()
  33265. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  33266. __decorate([
  33267. BABYLON.serialize()
  33268. ], ColorCurves.prototype, "_midtonesHue", void 0);
  33269. __decorate([
  33270. BABYLON.serialize()
  33271. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  33272. __decorate([
  33273. BABYLON.serialize()
  33274. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  33275. __decorate([
  33276. BABYLON.serialize()
  33277. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  33278. return ColorCurves;
  33279. }());
  33280. BABYLON.ColorCurves = ColorCurves;
  33281. })(BABYLON || (BABYLON = {}));
  33282. //# sourceMappingURL=babylon.colorCurves.js.map
  33283. var BABYLON;
  33284. (function (BABYLON) {
  33285. var StandardMaterialDefines = /** @class */ (function (_super) {
  33286. __extends(StandardMaterialDefines, _super);
  33287. function StandardMaterialDefines() {
  33288. var _this = _super.call(this) || this;
  33289. _this.MAINUV1 = false;
  33290. _this.MAINUV2 = false;
  33291. _this.DIFFUSE = false;
  33292. _this.DIFFUSEDIRECTUV = 0;
  33293. _this.AMBIENT = false;
  33294. _this.AMBIENTDIRECTUV = 0;
  33295. _this.OPACITY = false;
  33296. _this.OPACITYDIRECTUV = 0;
  33297. _this.OPACITYRGB = false;
  33298. _this.REFLECTION = false;
  33299. _this.EMISSIVE = false;
  33300. _this.EMISSIVEDIRECTUV = 0;
  33301. _this.SPECULAR = false;
  33302. _this.SPECULARDIRECTUV = 0;
  33303. _this.BUMP = false;
  33304. _this.BUMPDIRECTUV = 0;
  33305. _this.PARALLAX = false;
  33306. _this.PARALLAXOCCLUSION = false;
  33307. _this.SPECULAROVERALPHA = false;
  33308. _this.CLIPPLANE = false;
  33309. _this.ALPHATEST = false;
  33310. _this.DEPTHPREPASS = false;
  33311. _this.ALPHAFROMDIFFUSE = false;
  33312. _this.POINTSIZE = false;
  33313. _this.FOG = false;
  33314. _this.SPECULARTERM = false;
  33315. _this.DIFFUSEFRESNEL = false;
  33316. _this.OPACITYFRESNEL = false;
  33317. _this.REFLECTIONFRESNEL = false;
  33318. _this.REFRACTIONFRESNEL = false;
  33319. _this.EMISSIVEFRESNEL = false;
  33320. _this.FRESNEL = false;
  33321. _this.NORMAL = false;
  33322. _this.UV1 = false;
  33323. _this.UV2 = false;
  33324. _this.VERTEXCOLOR = false;
  33325. _this.VERTEXALPHA = false;
  33326. _this.NUM_BONE_INFLUENCERS = 0;
  33327. _this.BonesPerMesh = 0;
  33328. _this.INSTANCES = false;
  33329. _this.GLOSSINESS = false;
  33330. _this.ROUGHNESS = false;
  33331. _this.EMISSIVEASILLUMINATION = false;
  33332. _this.LINKEMISSIVEWITHDIFFUSE = false;
  33333. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  33334. _this.LIGHTMAP = false;
  33335. _this.LIGHTMAPDIRECTUV = 0;
  33336. _this.USELIGHTMAPASSHADOWMAP = false;
  33337. _this.REFLECTIONMAP_3D = false;
  33338. _this.REFLECTIONMAP_SPHERICAL = false;
  33339. _this.REFLECTIONMAP_PLANAR = false;
  33340. _this.REFLECTIONMAP_CUBIC = false;
  33341. _this.REFLECTIONMAP_PROJECTION = false;
  33342. _this.REFLECTIONMAP_SKYBOX = false;
  33343. _this.REFLECTIONMAP_EXPLICIT = false;
  33344. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  33345. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  33346. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  33347. _this.INVERTCUBICMAP = false;
  33348. _this.LOGARITHMICDEPTH = false;
  33349. _this.REFRACTION = false;
  33350. _this.REFRACTIONMAP_3D = false;
  33351. _this.REFLECTIONOVERALPHA = false;
  33352. _this.TWOSIDEDLIGHTING = false;
  33353. _this.SHADOWFLOAT = false;
  33354. _this.MORPHTARGETS = false;
  33355. _this.MORPHTARGETS_NORMAL = false;
  33356. _this.MORPHTARGETS_TANGENT = false;
  33357. _this.NUM_MORPH_INFLUENCERS = 0;
  33358. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  33359. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  33360. _this.IMAGEPROCESSING = false;
  33361. _this.VIGNETTE = false;
  33362. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  33363. _this.VIGNETTEBLENDMODEOPAQUE = false;
  33364. _this.TONEMAPPING = false;
  33365. _this.CONTRAST = false;
  33366. _this.COLORCURVES = false;
  33367. _this.COLORGRADING = false;
  33368. _this.COLORGRADING3D = false;
  33369. _this.SAMPLER3DGREENDEPTH = false;
  33370. _this.SAMPLER3DBGRMAP = false;
  33371. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  33372. _this.EXPOSURE = false;
  33373. _this.rebuild();
  33374. return _this;
  33375. }
  33376. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  33377. var modes = [
  33378. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  33379. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  33380. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  33381. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  33382. ];
  33383. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  33384. var mode = modes_1[_i];
  33385. this[mode] = (mode === modeToEnable);
  33386. }
  33387. };
  33388. return StandardMaterialDefines;
  33389. }(BABYLON.MaterialDefines));
  33390. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  33391. var StandardMaterial = /** @class */ (function (_super) {
  33392. __extends(StandardMaterial, _super);
  33393. function StandardMaterial(name, scene) {
  33394. var _this = _super.call(this, name, scene) || this;
  33395. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  33396. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  33397. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  33398. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  33399. _this.specularPower = 64;
  33400. _this._useAlphaFromDiffuseTexture = false;
  33401. _this._useEmissiveAsIllumination = false;
  33402. _this._linkEmissiveWithDiffuse = false;
  33403. _this._useSpecularOverAlpha = false;
  33404. _this._useReflectionOverAlpha = false;
  33405. _this._disableLighting = false;
  33406. _this._useParallax = false;
  33407. _this._useParallaxOcclusion = false;
  33408. _this.parallaxScaleBias = 0.05;
  33409. _this._roughness = 0;
  33410. _this.indexOfRefraction = 0.98;
  33411. _this.invertRefractionY = true;
  33412. _this._useLightmapAsShadowmap = false;
  33413. _this._useReflectionFresnelFromSpecular = false;
  33414. _this._useGlossinessFromSpecularMapAlpha = false;
  33415. _this._maxSimultaneousLights = 4;
  33416. /**
  33417. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  33418. */
  33419. _this._invertNormalMapX = false;
  33420. /**
  33421. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  33422. */
  33423. _this._invertNormalMapY = false;
  33424. /**
  33425. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  33426. */
  33427. _this._twoSidedLighting = false;
  33428. _this._renderTargets = new BABYLON.SmartArray(16);
  33429. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  33430. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  33431. // Setup the default processing configuration to the scene.
  33432. _this._attachImageProcessingConfiguration(null);
  33433. _this.getRenderTargetTextures = function () {
  33434. _this._renderTargets.reset();
  33435. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  33436. _this._renderTargets.push(_this._reflectionTexture);
  33437. }
  33438. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  33439. _this._renderTargets.push(_this._refractionTexture);
  33440. }
  33441. return _this._renderTargets;
  33442. };
  33443. return _this;
  33444. }
  33445. ;
  33446. ;
  33447. ;
  33448. ;
  33449. ;
  33450. ;
  33451. ;
  33452. ;
  33453. ;
  33454. ;
  33455. ;
  33456. ;
  33457. ;
  33458. ;
  33459. ;
  33460. ;
  33461. ;
  33462. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  33463. /**
  33464. * Gets the image processing configuration used either in this material.
  33465. */
  33466. get: function () {
  33467. return this._imageProcessingConfiguration;
  33468. },
  33469. /**
  33470. * Sets the Default image processing configuration used either in the this material.
  33471. *
  33472. * If sets to null, the scene one is in use.
  33473. */
  33474. set: function (value) {
  33475. this._attachImageProcessingConfiguration(value);
  33476. // Ensure the effect will be rebuilt.
  33477. this._markAllSubMeshesAsTexturesDirty();
  33478. },
  33479. enumerable: true,
  33480. configurable: true
  33481. });
  33482. /**
  33483. * Attaches a new image processing configuration to the Standard Material.
  33484. * @param configuration
  33485. */
  33486. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  33487. var _this = this;
  33488. if (configuration === this._imageProcessingConfiguration) {
  33489. return;
  33490. }
  33491. // Detaches observer.
  33492. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  33493. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  33494. }
  33495. // Pick the scene configuration if needed.
  33496. if (!configuration) {
  33497. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  33498. }
  33499. else {
  33500. this._imageProcessingConfiguration = configuration;
  33501. }
  33502. // Attaches observer.
  33503. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  33504. _this._markAllSubMeshesAsImageProcessingDirty();
  33505. });
  33506. };
  33507. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  33508. /**
  33509. * Gets wether the color curves effect is enabled.
  33510. */
  33511. get: function () {
  33512. return this.imageProcessingConfiguration.colorCurvesEnabled;
  33513. },
  33514. /**
  33515. * Sets wether the color curves effect is enabled.
  33516. */
  33517. set: function (value) {
  33518. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33519. },
  33520. enumerable: true,
  33521. configurable: true
  33522. });
  33523. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  33524. /**
  33525. * Gets wether the color grading effect is enabled.
  33526. */
  33527. get: function () {
  33528. return this.imageProcessingConfiguration.colorGradingEnabled;
  33529. },
  33530. /**
  33531. * Gets wether the color grading effect is enabled.
  33532. */
  33533. set: function (value) {
  33534. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33535. },
  33536. enumerable: true,
  33537. configurable: true
  33538. });
  33539. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  33540. /**
  33541. * Gets wether tonemapping is enabled or not.
  33542. */
  33543. get: function () {
  33544. return this._imageProcessingConfiguration.toneMappingEnabled;
  33545. },
  33546. /**
  33547. * Sets wether tonemapping is enabled or not
  33548. */
  33549. set: function (value) {
  33550. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33551. },
  33552. enumerable: true,
  33553. configurable: true
  33554. });
  33555. ;
  33556. ;
  33557. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  33558. /**
  33559. * The camera exposure used on this material.
  33560. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33561. * This corresponds to a photographic exposure.
  33562. */
  33563. get: function () {
  33564. return this._imageProcessingConfiguration.exposure;
  33565. },
  33566. /**
  33567. * The camera exposure used on this material.
  33568. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33569. * This corresponds to a photographic exposure.
  33570. */
  33571. set: function (value) {
  33572. this._imageProcessingConfiguration.exposure = value;
  33573. },
  33574. enumerable: true,
  33575. configurable: true
  33576. });
  33577. ;
  33578. ;
  33579. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  33580. /**
  33581. * Gets The camera contrast used on this material.
  33582. */
  33583. get: function () {
  33584. return this._imageProcessingConfiguration.contrast;
  33585. },
  33586. /**
  33587. * Sets The camera contrast used on this material.
  33588. */
  33589. set: function (value) {
  33590. this._imageProcessingConfiguration.contrast = value;
  33591. },
  33592. enumerable: true,
  33593. configurable: true
  33594. });
  33595. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  33596. /**
  33597. * Gets the Color Grading 2D Lookup Texture.
  33598. */
  33599. get: function () {
  33600. return this._imageProcessingConfiguration.colorGradingTexture;
  33601. },
  33602. /**
  33603. * Sets the Color Grading 2D Lookup Texture.
  33604. */
  33605. set: function (value) {
  33606. this._imageProcessingConfiguration.colorGradingTexture = value;
  33607. },
  33608. enumerable: true,
  33609. configurable: true
  33610. });
  33611. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  33612. /**
  33613. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33614. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33615. * 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;
  33616. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33617. */
  33618. get: function () {
  33619. return this._imageProcessingConfiguration.colorCurves;
  33620. },
  33621. /**
  33622. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33623. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33624. * 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;
  33625. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33626. */
  33627. set: function (value) {
  33628. this._imageProcessingConfiguration.colorCurves = value;
  33629. },
  33630. enumerable: true,
  33631. configurable: true
  33632. });
  33633. StandardMaterial.prototype.getClassName = function () {
  33634. return "StandardMaterial";
  33635. };
  33636. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  33637. get: function () {
  33638. return this._useLogarithmicDepth;
  33639. },
  33640. set: function (value) {
  33641. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  33642. this._markAllSubMeshesAsMiscDirty();
  33643. },
  33644. enumerable: true,
  33645. configurable: true
  33646. });
  33647. StandardMaterial.prototype.needAlphaBlending = function () {
  33648. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  33649. };
  33650. StandardMaterial.prototype.needAlphaTesting = function () {
  33651. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  33652. };
  33653. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  33654. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  33655. };
  33656. StandardMaterial.prototype.getAlphaTestTexture = function () {
  33657. return this._diffuseTexture;
  33658. };
  33659. /**
  33660. * Child classes can use it to update shaders
  33661. */
  33662. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  33663. if (useInstances === void 0) { useInstances = false; }
  33664. if (subMesh.effect && this.isFrozen) {
  33665. if (this._wasPreviouslyReady && subMesh.effect) {
  33666. return true;
  33667. }
  33668. }
  33669. if (!subMesh._materialDefines) {
  33670. subMesh._materialDefines = new StandardMaterialDefines();
  33671. }
  33672. var scene = this.getScene();
  33673. var defines = subMesh._materialDefines;
  33674. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  33675. if (defines._renderId === scene.getRenderId()) {
  33676. return true;
  33677. }
  33678. }
  33679. var engine = scene.getEngine();
  33680. // Lights
  33681. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  33682. // Textures
  33683. if (defines._areTexturesDirty) {
  33684. defines._needUVs = false;
  33685. defines.MAINUV1 = false;
  33686. defines.MAINUV2 = false;
  33687. if (scene.texturesEnabled) {
  33688. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  33689. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  33690. return false;
  33691. }
  33692. else {
  33693. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  33694. }
  33695. }
  33696. else {
  33697. defines.DIFFUSE = false;
  33698. }
  33699. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  33700. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  33701. return false;
  33702. }
  33703. else {
  33704. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  33705. }
  33706. }
  33707. else {
  33708. defines.AMBIENT = false;
  33709. }
  33710. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  33711. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  33712. return false;
  33713. }
  33714. else {
  33715. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  33716. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  33717. }
  33718. }
  33719. else {
  33720. defines.OPACITY = false;
  33721. }
  33722. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  33723. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  33724. return false;
  33725. }
  33726. else {
  33727. defines._needNormals = true;
  33728. defines.REFLECTION = true;
  33729. defines.ROUGHNESS = (this._roughness > 0);
  33730. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  33731. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  33732. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  33733. switch (this._reflectionTexture.coordinatesMode) {
  33734. case BABYLON.Texture.CUBIC_MODE:
  33735. case BABYLON.Texture.INVCUBIC_MODE:
  33736. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  33737. break;
  33738. case BABYLON.Texture.EXPLICIT_MODE:
  33739. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  33740. break;
  33741. case BABYLON.Texture.PLANAR_MODE:
  33742. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  33743. break;
  33744. case BABYLON.Texture.PROJECTION_MODE:
  33745. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  33746. break;
  33747. case BABYLON.Texture.SKYBOX_MODE:
  33748. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  33749. break;
  33750. case BABYLON.Texture.SPHERICAL_MODE:
  33751. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  33752. break;
  33753. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  33754. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  33755. break;
  33756. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  33757. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  33758. break;
  33759. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  33760. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  33761. break;
  33762. }
  33763. }
  33764. }
  33765. else {
  33766. defines.REFLECTION = false;
  33767. }
  33768. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  33769. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  33770. return false;
  33771. }
  33772. else {
  33773. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  33774. }
  33775. }
  33776. else {
  33777. defines.EMISSIVE = false;
  33778. }
  33779. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  33780. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  33781. return false;
  33782. }
  33783. else {
  33784. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  33785. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  33786. }
  33787. }
  33788. else {
  33789. defines.LIGHTMAP = false;
  33790. }
  33791. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  33792. if (!this._specularTexture.isReadyOrNotBlocking()) {
  33793. return false;
  33794. }
  33795. else {
  33796. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  33797. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  33798. }
  33799. }
  33800. else {
  33801. defines.SPECULAR = false;
  33802. }
  33803. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  33804. // Bump texure can not be not blocking.
  33805. if (!this._bumpTexture.isReady()) {
  33806. return false;
  33807. }
  33808. else {
  33809. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  33810. defines.PARALLAX = this._useParallax;
  33811. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  33812. }
  33813. }
  33814. else {
  33815. defines.BUMP = false;
  33816. }
  33817. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  33818. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  33819. return false;
  33820. }
  33821. else {
  33822. defines._needUVs = true;
  33823. defines.REFRACTION = true;
  33824. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  33825. }
  33826. }
  33827. else {
  33828. defines.REFRACTION = false;
  33829. }
  33830. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  33831. }
  33832. else {
  33833. defines.DIFFUSE = false;
  33834. defines.AMBIENT = false;
  33835. defines.OPACITY = false;
  33836. defines.REFLECTION = false;
  33837. defines.EMISSIVE = false;
  33838. defines.LIGHTMAP = false;
  33839. defines.BUMP = false;
  33840. defines.REFRACTION = false;
  33841. }
  33842. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  33843. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  33844. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  33845. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  33846. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  33847. }
  33848. if (defines._areImageProcessingDirty) {
  33849. if (!this._imageProcessingConfiguration.isReady()) {
  33850. return false;
  33851. }
  33852. this._imageProcessingConfiguration.prepareDefines(defines);
  33853. }
  33854. if (defines._areFresnelDirty) {
  33855. if (StandardMaterial.FresnelEnabled) {
  33856. // Fresnel
  33857. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  33858. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  33859. this._reflectionFresnelParameters) {
  33860. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  33861. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  33862. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  33863. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  33864. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  33865. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  33866. defines._needNormals = true;
  33867. defines.FRESNEL = true;
  33868. }
  33869. }
  33870. else {
  33871. defines.FRESNEL = false;
  33872. }
  33873. }
  33874. // Misc.
  33875. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  33876. // Attribs
  33877. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  33878. // Values that need to be evaluated on every frame
  33879. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  33880. // Get correct effect
  33881. if (defines.isDirty) {
  33882. defines.markAsProcessed();
  33883. scene.resetCachedMaterial();
  33884. // Fallbacks
  33885. var fallbacks = new BABYLON.EffectFallbacks();
  33886. if (defines.REFLECTION) {
  33887. fallbacks.addFallback(0, "REFLECTION");
  33888. }
  33889. if (defines.SPECULAR) {
  33890. fallbacks.addFallback(0, "SPECULAR");
  33891. }
  33892. if (defines.BUMP) {
  33893. fallbacks.addFallback(0, "BUMP");
  33894. }
  33895. if (defines.PARALLAX) {
  33896. fallbacks.addFallback(1, "PARALLAX");
  33897. }
  33898. if (defines.PARALLAXOCCLUSION) {
  33899. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  33900. }
  33901. if (defines.SPECULAROVERALPHA) {
  33902. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  33903. }
  33904. if (defines.FOG) {
  33905. fallbacks.addFallback(1, "FOG");
  33906. }
  33907. if (defines.POINTSIZE) {
  33908. fallbacks.addFallback(0, "POINTSIZE");
  33909. }
  33910. if (defines.LOGARITHMICDEPTH) {
  33911. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  33912. }
  33913. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  33914. if (defines.SPECULARTERM) {
  33915. fallbacks.addFallback(0, "SPECULARTERM");
  33916. }
  33917. if (defines.DIFFUSEFRESNEL) {
  33918. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  33919. }
  33920. if (defines.OPACITYFRESNEL) {
  33921. fallbacks.addFallback(2, "OPACITYFRESNEL");
  33922. }
  33923. if (defines.REFLECTIONFRESNEL) {
  33924. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  33925. }
  33926. if (defines.EMISSIVEFRESNEL) {
  33927. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  33928. }
  33929. if (defines.FRESNEL) {
  33930. fallbacks.addFallback(4, "FRESNEL");
  33931. }
  33932. //Attributes
  33933. var attribs = [BABYLON.VertexBuffer.PositionKind];
  33934. if (defines.NORMAL) {
  33935. attribs.push(BABYLON.VertexBuffer.NormalKind);
  33936. }
  33937. if (defines.UV1) {
  33938. attribs.push(BABYLON.VertexBuffer.UVKind);
  33939. }
  33940. if (defines.UV2) {
  33941. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  33942. }
  33943. if (defines.VERTEXCOLOR) {
  33944. attribs.push(BABYLON.VertexBuffer.ColorKind);
  33945. }
  33946. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  33947. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  33948. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  33949. var shaderName = "default";
  33950. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  33951. "vFogInfos", "vFogColor", "pointSize",
  33952. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  33953. "mBones",
  33954. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  33955. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  33956. "logarithmicDepthConstant", "vTangentSpaceParams"
  33957. ];
  33958. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  33959. var uniformBuffers = ["Material", "Scene"];
  33960. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  33961. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  33962. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  33963. uniformsNames: uniforms,
  33964. uniformBuffersNames: uniformBuffers,
  33965. samplers: samplers,
  33966. defines: defines,
  33967. maxSimultaneousLights: this._maxSimultaneousLights
  33968. });
  33969. if (this.customShaderNameResolve) {
  33970. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  33971. }
  33972. var join = defines.toString();
  33973. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  33974. attributes: attribs,
  33975. uniformsNames: uniforms,
  33976. uniformBuffersNames: uniformBuffers,
  33977. samplers: samplers,
  33978. defines: join,
  33979. fallbacks: fallbacks,
  33980. onCompiled: this.onCompiled,
  33981. onError: this.onError,
  33982. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  33983. }, engine), defines);
  33984. this.buildUniformLayout();
  33985. }
  33986. if (!subMesh.effect || !subMesh.effect.isReady()) {
  33987. return false;
  33988. }
  33989. defines._renderId = scene.getRenderId();
  33990. this._wasPreviouslyReady = true;
  33991. return true;
  33992. };
  33993. StandardMaterial.prototype.buildUniformLayout = function () {
  33994. // Order is important !
  33995. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  33996. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  33997. this._uniformBuffer.addUniform("opacityParts", 4);
  33998. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  33999. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  34000. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  34001. this._uniformBuffer.addUniform("refractionRightColor", 4);
  34002. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  34003. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  34004. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  34005. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  34006. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  34007. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  34008. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  34009. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  34010. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  34011. this._uniformBuffer.addUniform("vBumpInfos", 3);
  34012. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  34013. this._uniformBuffer.addUniform("ambientMatrix", 16);
  34014. this._uniformBuffer.addUniform("opacityMatrix", 16);
  34015. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  34016. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  34017. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  34018. this._uniformBuffer.addUniform("specularMatrix", 16);
  34019. this._uniformBuffer.addUniform("bumpMatrix", 16);
  34020. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  34021. this._uniformBuffer.addUniform("refractionMatrix", 16);
  34022. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  34023. this._uniformBuffer.addUniform("vSpecularColor", 4);
  34024. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  34025. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  34026. this._uniformBuffer.addUniform("pointSize", 1);
  34027. this._uniformBuffer.create();
  34028. };
  34029. StandardMaterial.prototype.unbind = function () {
  34030. if (this._activeEffect) {
  34031. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  34032. this._activeEffect.setTexture("reflection2DSampler", null);
  34033. }
  34034. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  34035. this._activeEffect.setTexture("refraction2DSampler", null);
  34036. }
  34037. }
  34038. _super.prototype.unbind.call(this);
  34039. };
  34040. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34041. var scene = this.getScene();
  34042. var defines = subMesh._materialDefines;
  34043. if (!defines) {
  34044. return;
  34045. }
  34046. var effect = subMesh.effect;
  34047. if (!effect) {
  34048. return;
  34049. }
  34050. this._activeEffect = effect;
  34051. // Matrices
  34052. this.bindOnlyWorldMatrix(world);
  34053. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  34054. // Bones
  34055. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  34056. if (mustRebind) {
  34057. this._uniformBuffer.bindToEffect(effect, "Material");
  34058. this.bindViewProjection(effect);
  34059. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  34060. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  34061. // Fresnel
  34062. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  34063. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  34064. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  34065. }
  34066. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  34067. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  34068. }
  34069. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  34070. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  34071. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  34072. }
  34073. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  34074. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  34075. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  34076. }
  34077. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  34078. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  34079. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  34080. }
  34081. }
  34082. // Textures
  34083. if (scene.texturesEnabled) {
  34084. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34085. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  34086. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  34087. }
  34088. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34089. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  34090. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  34091. }
  34092. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34093. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  34094. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  34095. }
  34096. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34097. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  34098. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  34099. }
  34100. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34101. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  34102. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  34103. }
  34104. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34105. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  34106. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  34107. }
  34108. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34109. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  34110. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  34111. }
  34112. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34113. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  34114. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  34115. if (scene._mirroredCameraPosition) {
  34116. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  34117. }
  34118. else {
  34119. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  34120. }
  34121. }
  34122. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34123. var depth = 1.0;
  34124. if (!this._refractionTexture.isCube) {
  34125. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  34126. if (this._refractionTexture.depth) {
  34127. depth = this._refractionTexture.depth;
  34128. }
  34129. }
  34130. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  34131. }
  34132. }
  34133. // Point size
  34134. if (this.pointsCloud) {
  34135. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  34136. }
  34137. if (defines.SPECULARTERM) {
  34138. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  34139. }
  34140. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  34141. // Diffuse
  34142. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  34143. }
  34144. // Textures
  34145. if (scene.texturesEnabled) {
  34146. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34147. effect.setTexture("diffuseSampler", this._diffuseTexture);
  34148. }
  34149. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  34150. effect.setTexture("ambientSampler", this._ambientTexture);
  34151. }
  34152. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  34153. effect.setTexture("opacitySampler", this._opacityTexture);
  34154. }
  34155. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  34156. if (this._reflectionTexture.isCube) {
  34157. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  34158. }
  34159. else {
  34160. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  34161. }
  34162. }
  34163. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  34164. effect.setTexture("emissiveSampler", this._emissiveTexture);
  34165. }
  34166. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  34167. effect.setTexture("lightmapSampler", this._lightmapTexture);
  34168. }
  34169. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  34170. effect.setTexture("specularSampler", this._specularTexture);
  34171. }
  34172. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  34173. effect.setTexture("bumpSampler", this._bumpTexture);
  34174. }
  34175. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  34176. var depth = 1.0;
  34177. if (this._refractionTexture.isCube) {
  34178. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  34179. }
  34180. else {
  34181. effect.setTexture("refraction2DSampler", this._refractionTexture);
  34182. }
  34183. }
  34184. }
  34185. // Clip plane
  34186. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  34187. // Colors
  34188. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  34189. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  34190. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  34191. }
  34192. if (mustRebind || !this.isFrozen) {
  34193. // Lights
  34194. if (scene.lightsEnabled && !this._disableLighting) {
  34195. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  34196. }
  34197. // View
  34198. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  34199. this.bindView(effect);
  34200. }
  34201. // Fog
  34202. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  34203. // Morph targets
  34204. if (defines.NUM_MORPH_INFLUENCERS) {
  34205. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  34206. }
  34207. // Log. depth
  34208. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  34209. // image processing
  34210. this._imageProcessingConfiguration.bind(this._activeEffect);
  34211. }
  34212. this._uniformBuffer.update();
  34213. this._afterBind(mesh, this._activeEffect);
  34214. };
  34215. StandardMaterial.prototype.getAnimatables = function () {
  34216. var results = [];
  34217. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  34218. results.push(this._diffuseTexture);
  34219. }
  34220. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  34221. results.push(this._ambientTexture);
  34222. }
  34223. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  34224. results.push(this._opacityTexture);
  34225. }
  34226. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  34227. results.push(this._reflectionTexture);
  34228. }
  34229. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  34230. results.push(this._emissiveTexture);
  34231. }
  34232. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  34233. results.push(this._specularTexture);
  34234. }
  34235. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  34236. results.push(this._bumpTexture);
  34237. }
  34238. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  34239. results.push(this._lightmapTexture);
  34240. }
  34241. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  34242. results.push(this._refractionTexture);
  34243. }
  34244. return results;
  34245. };
  34246. StandardMaterial.prototype.getActiveTextures = function () {
  34247. var activeTextures = _super.prototype.getActiveTextures.call(this);
  34248. if (this._diffuseTexture) {
  34249. activeTextures.push(this._diffuseTexture);
  34250. }
  34251. if (this._ambientTexture) {
  34252. activeTextures.push(this._ambientTexture);
  34253. }
  34254. if (this._opacityTexture) {
  34255. activeTextures.push(this._opacityTexture);
  34256. }
  34257. if (this._reflectionTexture) {
  34258. activeTextures.push(this._reflectionTexture);
  34259. }
  34260. if (this._emissiveTexture) {
  34261. activeTextures.push(this._emissiveTexture);
  34262. }
  34263. if (this._specularTexture) {
  34264. activeTextures.push(this._specularTexture);
  34265. }
  34266. if (this._bumpTexture) {
  34267. activeTextures.push(this._bumpTexture);
  34268. }
  34269. if (this._lightmapTexture) {
  34270. activeTextures.push(this._lightmapTexture);
  34271. }
  34272. if (this._refractionTexture) {
  34273. activeTextures.push(this._refractionTexture);
  34274. }
  34275. return activeTextures;
  34276. };
  34277. StandardMaterial.prototype.hasTexture = function (texture) {
  34278. if (_super.prototype.hasTexture.call(this, texture)) {
  34279. return true;
  34280. }
  34281. if (this._diffuseTexture === texture) {
  34282. return true;
  34283. }
  34284. if (this._ambientTexture === texture) {
  34285. return true;
  34286. }
  34287. if (this._opacityTexture === texture) {
  34288. return true;
  34289. }
  34290. if (this._reflectionTexture === texture) {
  34291. return true;
  34292. }
  34293. if (this._emissiveTexture === texture) {
  34294. return true;
  34295. }
  34296. if (this._specularTexture === texture) {
  34297. return true;
  34298. }
  34299. if (this._bumpTexture === texture) {
  34300. return true;
  34301. }
  34302. if (this._lightmapTexture === texture) {
  34303. return true;
  34304. }
  34305. if (this._refractionTexture === texture) {
  34306. return true;
  34307. }
  34308. return false;
  34309. };
  34310. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  34311. if (forceDisposeTextures) {
  34312. if (this._diffuseTexture) {
  34313. this._diffuseTexture.dispose();
  34314. }
  34315. if (this._ambientTexture) {
  34316. this._ambientTexture.dispose();
  34317. }
  34318. if (this._opacityTexture) {
  34319. this._opacityTexture.dispose();
  34320. }
  34321. if (this._reflectionTexture) {
  34322. this._reflectionTexture.dispose();
  34323. }
  34324. if (this._emissiveTexture) {
  34325. this._emissiveTexture.dispose();
  34326. }
  34327. if (this._specularTexture) {
  34328. this._specularTexture.dispose();
  34329. }
  34330. if (this._bumpTexture) {
  34331. this._bumpTexture.dispose();
  34332. }
  34333. if (this._lightmapTexture) {
  34334. this._lightmapTexture.dispose();
  34335. }
  34336. if (this._refractionTexture) {
  34337. this._refractionTexture.dispose();
  34338. }
  34339. }
  34340. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34341. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34342. }
  34343. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  34344. };
  34345. StandardMaterial.prototype.clone = function (name) {
  34346. var _this = this;
  34347. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  34348. result.name = name;
  34349. result.id = name;
  34350. return result;
  34351. };
  34352. StandardMaterial.prototype.serialize = function () {
  34353. return BABYLON.SerializationHelper.Serialize(this);
  34354. };
  34355. // Statics
  34356. StandardMaterial.Parse = function (source, scene, rootUrl) {
  34357. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  34358. };
  34359. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  34360. get: function () {
  34361. return StandardMaterial._DiffuseTextureEnabled;
  34362. },
  34363. set: function (value) {
  34364. if (StandardMaterial._DiffuseTextureEnabled === value) {
  34365. return;
  34366. }
  34367. StandardMaterial._DiffuseTextureEnabled = value;
  34368. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34369. },
  34370. enumerable: true,
  34371. configurable: true
  34372. });
  34373. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  34374. get: function () {
  34375. return StandardMaterial._AmbientTextureEnabled;
  34376. },
  34377. set: function (value) {
  34378. if (StandardMaterial._AmbientTextureEnabled === value) {
  34379. return;
  34380. }
  34381. StandardMaterial._AmbientTextureEnabled = value;
  34382. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34383. },
  34384. enumerable: true,
  34385. configurable: true
  34386. });
  34387. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  34388. get: function () {
  34389. return StandardMaterial._OpacityTextureEnabled;
  34390. },
  34391. set: function (value) {
  34392. if (StandardMaterial._OpacityTextureEnabled === value) {
  34393. return;
  34394. }
  34395. StandardMaterial._OpacityTextureEnabled = value;
  34396. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34397. },
  34398. enumerable: true,
  34399. configurable: true
  34400. });
  34401. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  34402. get: function () {
  34403. return StandardMaterial._ReflectionTextureEnabled;
  34404. },
  34405. set: function (value) {
  34406. if (StandardMaterial._ReflectionTextureEnabled === value) {
  34407. return;
  34408. }
  34409. StandardMaterial._ReflectionTextureEnabled = value;
  34410. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34411. },
  34412. enumerable: true,
  34413. configurable: true
  34414. });
  34415. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  34416. get: function () {
  34417. return StandardMaterial._EmissiveTextureEnabled;
  34418. },
  34419. set: function (value) {
  34420. if (StandardMaterial._EmissiveTextureEnabled === value) {
  34421. return;
  34422. }
  34423. StandardMaterial._EmissiveTextureEnabled = value;
  34424. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34425. },
  34426. enumerable: true,
  34427. configurable: true
  34428. });
  34429. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  34430. get: function () {
  34431. return StandardMaterial._SpecularTextureEnabled;
  34432. },
  34433. set: function (value) {
  34434. if (StandardMaterial._SpecularTextureEnabled === value) {
  34435. return;
  34436. }
  34437. StandardMaterial._SpecularTextureEnabled = value;
  34438. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34439. },
  34440. enumerable: true,
  34441. configurable: true
  34442. });
  34443. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  34444. get: function () {
  34445. return StandardMaterial._BumpTextureEnabled;
  34446. },
  34447. set: function (value) {
  34448. if (StandardMaterial._BumpTextureEnabled === value) {
  34449. return;
  34450. }
  34451. StandardMaterial._BumpTextureEnabled = value;
  34452. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34453. },
  34454. enumerable: true,
  34455. configurable: true
  34456. });
  34457. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  34458. get: function () {
  34459. return StandardMaterial._LightmapTextureEnabled;
  34460. },
  34461. set: function (value) {
  34462. if (StandardMaterial._LightmapTextureEnabled === value) {
  34463. return;
  34464. }
  34465. StandardMaterial._LightmapTextureEnabled = value;
  34466. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34467. },
  34468. enumerable: true,
  34469. configurable: true
  34470. });
  34471. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  34472. get: function () {
  34473. return StandardMaterial._RefractionTextureEnabled;
  34474. },
  34475. set: function (value) {
  34476. if (StandardMaterial._RefractionTextureEnabled === value) {
  34477. return;
  34478. }
  34479. StandardMaterial._RefractionTextureEnabled = value;
  34480. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34481. },
  34482. enumerable: true,
  34483. configurable: true
  34484. });
  34485. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  34486. get: function () {
  34487. return StandardMaterial._ColorGradingTextureEnabled;
  34488. },
  34489. set: function (value) {
  34490. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  34491. return;
  34492. }
  34493. StandardMaterial._ColorGradingTextureEnabled = value;
  34494. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  34495. },
  34496. enumerable: true,
  34497. configurable: true
  34498. });
  34499. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  34500. get: function () {
  34501. return StandardMaterial._FresnelEnabled;
  34502. },
  34503. set: function (value) {
  34504. if (StandardMaterial._FresnelEnabled === value) {
  34505. return;
  34506. }
  34507. StandardMaterial._FresnelEnabled = value;
  34508. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  34509. },
  34510. enumerable: true,
  34511. configurable: true
  34512. });
  34513. // Flags used to enable or disable a type of texture for all Standard Materials
  34514. StandardMaterial._DiffuseTextureEnabled = true;
  34515. StandardMaterial._AmbientTextureEnabled = true;
  34516. StandardMaterial._OpacityTextureEnabled = true;
  34517. StandardMaterial._ReflectionTextureEnabled = true;
  34518. StandardMaterial._EmissiveTextureEnabled = true;
  34519. StandardMaterial._SpecularTextureEnabled = true;
  34520. StandardMaterial._BumpTextureEnabled = true;
  34521. StandardMaterial._LightmapTextureEnabled = true;
  34522. StandardMaterial._RefractionTextureEnabled = true;
  34523. StandardMaterial._ColorGradingTextureEnabled = true;
  34524. StandardMaterial._FresnelEnabled = true;
  34525. __decorate([
  34526. BABYLON.serializeAsTexture("diffuseTexture")
  34527. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  34528. __decorate([
  34529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34530. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  34531. __decorate([
  34532. BABYLON.serializeAsTexture("ambientTexture")
  34533. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  34534. __decorate([
  34535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34536. ], StandardMaterial.prototype, "ambientTexture", void 0);
  34537. __decorate([
  34538. BABYLON.serializeAsTexture("opacityTexture")
  34539. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  34540. __decorate([
  34541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34542. ], StandardMaterial.prototype, "opacityTexture", void 0);
  34543. __decorate([
  34544. BABYLON.serializeAsTexture("reflectionTexture")
  34545. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  34546. __decorate([
  34547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34548. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  34549. __decorate([
  34550. BABYLON.serializeAsTexture("emissiveTexture")
  34551. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  34552. __decorate([
  34553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34554. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  34555. __decorate([
  34556. BABYLON.serializeAsTexture("specularTexture")
  34557. ], StandardMaterial.prototype, "_specularTexture", void 0);
  34558. __decorate([
  34559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34560. ], StandardMaterial.prototype, "specularTexture", void 0);
  34561. __decorate([
  34562. BABYLON.serializeAsTexture("bumpTexture")
  34563. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  34564. __decorate([
  34565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34566. ], StandardMaterial.prototype, "bumpTexture", void 0);
  34567. __decorate([
  34568. BABYLON.serializeAsTexture("lightmapTexture")
  34569. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  34570. __decorate([
  34571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34572. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  34573. __decorate([
  34574. BABYLON.serializeAsTexture("refractionTexture")
  34575. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  34576. __decorate([
  34577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34578. ], StandardMaterial.prototype, "refractionTexture", void 0);
  34579. __decorate([
  34580. BABYLON.serializeAsColor3("ambient")
  34581. ], StandardMaterial.prototype, "ambientColor", void 0);
  34582. __decorate([
  34583. BABYLON.serializeAsColor3("diffuse")
  34584. ], StandardMaterial.prototype, "diffuseColor", void 0);
  34585. __decorate([
  34586. BABYLON.serializeAsColor3("specular")
  34587. ], StandardMaterial.prototype, "specularColor", void 0);
  34588. __decorate([
  34589. BABYLON.serializeAsColor3("emissive")
  34590. ], StandardMaterial.prototype, "emissiveColor", void 0);
  34591. __decorate([
  34592. BABYLON.serialize()
  34593. ], StandardMaterial.prototype, "specularPower", void 0);
  34594. __decorate([
  34595. BABYLON.serialize("useAlphaFromDiffuseTexture")
  34596. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  34597. __decorate([
  34598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34599. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  34600. __decorate([
  34601. BABYLON.serialize("useEmissiveAsIllumination")
  34602. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  34603. __decorate([
  34604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34605. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  34606. __decorate([
  34607. BABYLON.serialize("linkEmissiveWithDiffuse")
  34608. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  34609. __decorate([
  34610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34611. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  34612. __decorate([
  34613. BABYLON.serialize("useSpecularOverAlpha")
  34614. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  34615. __decorate([
  34616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34617. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  34618. __decorate([
  34619. BABYLON.serialize("useReflectionOverAlpha")
  34620. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  34621. __decorate([
  34622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34623. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  34624. __decorate([
  34625. BABYLON.serialize("disableLighting")
  34626. ], StandardMaterial.prototype, "_disableLighting", void 0);
  34627. __decorate([
  34628. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34629. ], StandardMaterial.prototype, "disableLighting", void 0);
  34630. __decorate([
  34631. BABYLON.serialize("useParallax")
  34632. ], StandardMaterial.prototype, "_useParallax", void 0);
  34633. __decorate([
  34634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34635. ], StandardMaterial.prototype, "useParallax", void 0);
  34636. __decorate([
  34637. BABYLON.serialize("useParallaxOcclusion")
  34638. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  34639. __decorate([
  34640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34641. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  34642. __decorate([
  34643. BABYLON.serialize()
  34644. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  34645. __decorate([
  34646. BABYLON.serialize("roughness")
  34647. ], StandardMaterial.prototype, "_roughness", void 0);
  34648. __decorate([
  34649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34650. ], StandardMaterial.prototype, "roughness", void 0);
  34651. __decorate([
  34652. BABYLON.serialize()
  34653. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  34654. __decorate([
  34655. BABYLON.serialize()
  34656. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  34657. __decorate([
  34658. BABYLON.serialize("useLightmapAsShadowmap")
  34659. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  34660. __decorate([
  34661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34662. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  34663. __decorate([
  34664. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  34665. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  34666. __decorate([
  34667. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34668. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  34669. __decorate([
  34670. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  34671. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  34672. __decorate([
  34673. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34674. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  34675. __decorate([
  34676. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  34677. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  34678. __decorate([
  34679. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34680. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  34681. __decorate([
  34682. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  34683. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  34684. __decorate([
  34685. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34686. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  34687. __decorate([
  34688. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  34689. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  34690. __decorate([
  34691. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34692. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  34693. __decorate([
  34694. BABYLON.serialize("useReflectionFresnelFromSpecular")
  34695. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  34696. __decorate([
  34697. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  34698. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  34699. __decorate([
  34700. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  34701. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  34702. __decorate([
  34703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34704. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  34705. __decorate([
  34706. BABYLON.serialize("maxSimultaneousLights")
  34707. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  34708. __decorate([
  34709. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  34710. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  34711. __decorate([
  34712. BABYLON.serialize("invertNormalMapX")
  34713. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  34714. __decorate([
  34715. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34716. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  34717. __decorate([
  34718. BABYLON.serialize("invertNormalMapY")
  34719. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  34720. __decorate([
  34721. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34722. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  34723. __decorate([
  34724. BABYLON.serialize("twoSidedLighting")
  34725. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  34726. __decorate([
  34727. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  34728. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  34729. __decorate([
  34730. BABYLON.serialize()
  34731. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  34732. return StandardMaterial;
  34733. }(BABYLON.PushMaterial));
  34734. BABYLON.StandardMaterial = StandardMaterial;
  34735. })(BABYLON || (BABYLON = {}));
  34736. //# sourceMappingURL=babylon.standardMaterial.js.map
  34737. var BABYLON;
  34738. (function (BABYLON) {
  34739. var PBRMaterialDefines = /** @class */ (function (_super) {
  34740. __extends(PBRMaterialDefines, _super);
  34741. function PBRMaterialDefines() {
  34742. var _this = _super.call(this) || this;
  34743. _this.PBR = true;
  34744. _this.MAINUV1 = false;
  34745. _this.MAINUV2 = false;
  34746. _this.UV1 = false;
  34747. _this.UV2 = false;
  34748. _this.ALBEDO = false;
  34749. _this.ALBEDODIRECTUV = 0;
  34750. _this.VERTEXCOLOR = false;
  34751. _this.AMBIENT = false;
  34752. _this.AMBIENTDIRECTUV = 0;
  34753. _this.AMBIENTINGRAYSCALE = false;
  34754. _this.OPACITY = false;
  34755. _this.VERTEXALPHA = false;
  34756. _this.OPACITYDIRECTUV = 0;
  34757. _this.OPACITYRGB = false;
  34758. _this.ALPHATEST = false;
  34759. _this.DEPTHPREPASS = false;
  34760. _this.ALPHABLEND = false;
  34761. _this.ALPHAFROMALBEDO = false;
  34762. _this.ALPHATESTVALUE = 0.5;
  34763. _this.SPECULAROVERALPHA = false;
  34764. _this.RADIANCEOVERALPHA = false;
  34765. _this.ALPHAFRESNEL = false;
  34766. _this.PREMULTIPLYALPHA = false;
  34767. _this.EMISSIVE = false;
  34768. _this.EMISSIVEDIRECTUV = 0;
  34769. _this.REFLECTIVITY = false;
  34770. _this.REFLECTIVITYDIRECTUV = 0;
  34771. _this.SPECULARTERM = false;
  34772. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  34773. _this.MICROSURFACEAUTOMATIC = false;
  34774. _this.LODBASEDMICROSFURACE = false;
  34775. _this.MICROSURFACEMAP = false;
  34776. _this.MICROSURFACEMAPDIRECTUV = 0;
  34777. _this.METALLICWORKFLOW = false;
  34778. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  34779. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  34780. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  34781. _this.AOSTOREINMETALMAPRED = false;
  34782. _this.ENVIRONMENTBRDF = false;
  34783. _this.NORMAL = false;
  34784. _this.TANGENT = false;
  34785. _this.BUMP = false;
  34786. _this.BUMPDIRECTUV = 0;
  34787. _this.PARALLAX = false;
  34788. _this.PARALLAXOCCLUSION = false;
  34789. _this.NORMALXYSCALE = true;
  34790. _this.LIGHTMAP = false;
  34791. _this.LIGHTMAPDIRECTUV = 0;
  34792. _this.USELIGHTMAPASSHADOWMAP = false;
  34793. _this.REFLECTION = false;
  34794. _this.REFLECTIONMAP_3D = false;
  34795. _this.REFLECTIONMAP_SPHERICAL = false;
  34796. _this.REFLECTIONMAP_PLANAR = false;
  34797. _this.REFLECTIONMAP_CUBIC = false;
  34798. _this.REFLECTIONMAP_PROJECTION = false;
  34799. _this.REFLECTIONMAP_SKYBOX = false;
  34800. _this.REFLECTIONMAP_EXPLICIT = false;
  34801. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34802. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34803. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34804. _this.INVERTCUBICMAP = false;
  34805. _this.USESPHERICALFROMREFLECTIONMAP = false;
  34806. _this.USESPHERICALINVERTEX = false;
  34807. _this.REFLECTIONMAP_OPPOSITEZ = false;
  34808. _this.LODINREFLECTIONALPHA = false;
  34809. _this.GAMMAREFLECTION = false;
  34810. _this.REFRACTION = false;
  34811. _this.REFRACTIONMAP_3D = false;
  34812. _this.REFRACTIONMAP_OPPOSITEZ = false;
  34813. _this.LODINREFRACTIONALPHA = false;
  34814. _this.GAMMAREFRACTION = false;
  34815. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  34816. _this.INSTANCES = false;
  34817. _this.NUM_BONE_INFLUENCERS = 0;
  34818. _this.BonesPerMesh = 0;
  34819. _this.NONUNIFORMSCALING = false;
  34820. _this.MORPHTARGETS = false;
  34821. _this.MORPHTARGETS_NORMAL = false;
  34822. _this.MORPHTARGETS_TANGENT = false;
  34823. _this.NUM_MORPH_INFLUENCERS = 0;
  34824. _this.IMAGEPROCESSING = false;
  34825. _this.VIGNETTE = false;
  34826. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34827. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34828. _this.TONEMAPPING = false;
  34829. _this.CONTRAST = false;
  34830. _this.COLORCURVES = false;
  34831. _this.COLORGRADING = false;
  34832. _this.COLORGRADING3D = false;
  34833. _this.SAMPLER3DGREENDEPTH = false;
  34834. _this.SAMPLER3DBGRMAP = false;
  34835. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34836. _this.EXPOSURE = false;
  34837. _this.USEPHYSICALLIGHTFALLOFF = false;
  34838. _this.TWOSIDEDLIGHTING = false;
  34839. _this.SHADOWFLOAT = false;
  34840. _this.CLIPPLANE = false;
  34841. _this.POINTSIZE = false;
  34842. _this.FOG = false;
  34843. _this.LOGARITHMICDEPTH = false;
  34844. _this.FORCENORMALFORWARD = false;
  34845. _this.rebuild();
  34846. return _this;
  34847. }
  34848. PBRMaterialDefines.prototype.reset = function () {
  34849. _super.prototype.reset.call(this);
  34850. this.ALPHATESTVALUE = 0.5;
  34851. this.PBR = true;
  34852. };
  34853. return PBRMaterialDefines;
  34854. }(BABYLON.MaterialDefines));
  34855. /**
  34856. * The Physically based material base class of BJS.
  34857. *
  34858. * This offers the main features of a standard PBR material.
  34859. * For more information, please refer to the documentation :
  34860. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  34861. */
  34862. var PBRBaseMaterial = /** @class */ (function (_super) {
  34863. __extends(PBRBaseMaterial, _super);
  34864. /**
  34865. * Instantiates a new PBRMaterial instance.
  34866. *
  34867. * @param name The material name
  34868. * @param scene The scene the material will be use in.
  34869. */
  34870. function PBRBaseMaterial(name, scene) {
  34871. var _this = _super.call(this, name, scene) || this;
  34872. /**
  34873. * Intensity of the direct lights e.g. the four lights available in your scene.
  34874. * This impacts both the direct diffuse and specular highlights.
  34875. */
  34876. _this._directIntensity = 1.0;
  34877. /**
  34878. * Intensity of the emissive part of the material.
  34879. * This helps controlling the emissive effect without modifying the emissive color.
  34880. */
  34881. _this._emissiveIntensity = 1.0;
  34882. /**
  34883. * Intensity of the environment e.g. how much the environment will light the object
  34884. * either through harmonics for rough material or through the refelction for shiny ones.
  34885. */
  34886. _this._environmentIntensity = 1.0;
  34887. /**
  34888. * This is a special control allowing the reduction of the specular highlights coming from the
  34889. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  34890. */
  34891. _this._specularIntensity = 1.0;
  34892. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  34893. /**
  34894. * Debug Control allowing disabling the bump map on this material.
  34895. */
  34896. _this._disableBumpMap = false;
  34897. /**
  34898. * AKA Occlusion Texture Intensity in other nomenclature.
  34899. */
  34900. _this._ambientTextureStrength = 1.0;
  34901. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  34902. /**
  34903. * AKA Diffuse Color in other nomenclature.
  34904. */
  34905. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  34906. /**
  34907. * AKA Specular Color in other nomenclature.
  34908. */
  34909. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  34910. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  34911. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  34912. /**
  34913. * AKA Glossiness in other nomenclature.
  34914. */
  34915. _this._microSurface = 0.9;
  34916. /**
  34917. * source material index of refraction (IOR)' / 'destination material IOR.
  34918. */
  34919. _this._indexOfRefraction = 0.66;
  34920. /**
  34921. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  34922. */
  34923. _this._invertRefractionY = false;
  34924. /**
  34925. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  34926. * Materials half opaque for instance using refraction could benefit from this control.
  34927. */
  34928. _this._linkRefractionWithTransparency = false;
  34929. _this._useLightmapAsShadowmap = false;
  34930. /**
  34931. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  34932. */
  34933. _this._useAlphaFromAlbedoTexture = false;
  34934. /**
  34935. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  34936. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  34937. */
  34938. _this._useSpecularOverAlpha = true;
  34939. /**
  34940. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  34941. */
  34942. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  34943. /**
  34944. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  34945. */
  34946. _this._useRoughnessFromMetallicTextureAlpha = true;
  34947. /**
  34948. * Specifies if the metallic texture contains the roughness information in its green channel.
  34949. */
  34950. _this._useRoughnessFromMetallicTextureGreen = false;
  34951. /**
  34952. * Specifies if the metallic texture contains the metallness information in its blue channel.
  34953. */
  34954. _this._useMetallnessFromMetallicTextureBlue = false;
  34955. /**
  34956. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  34957. */
  34958. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  34959. /**
  34960. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  34961. */
  34962. _this._useAmbientInGrayScale = false;
  34963. /**
  34964. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  34965. * The material will try to infer what glossiness each pixel should be.
  34966. */
  34967. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  34968. /**
  34969. * BJS is using an harcoded light falloff based on a manually sets up range.
  34970. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  34971. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  34972. */
  34973. _this._usePhysicalLightFalloff = true;
  34974. /**
  34975. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  34976. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  34977. */
  34978. _this._useRadianceOverAlpha = true;
  34979. /**
  34980. * Allows using the bump map in parallax mode.
  34981. */
  34982. _this._useParallax = false;
  34983. /**
  34984. * Allows using the bump map in parallax occlusion mode.
  34985. */
  34986. _this._useParallaxOcclusion = false;
  34987. /**
  34988. * Controls the scale bias of the parallax mode.
  34989. */
  34990. _this._parallaxScaleBias = 0.05;
  34991. /**
  34992. * If sets to true, disables all the lights affecting the material.
  34993. */
  34994. _this._disableLighting = false;
  34995. /**
  34996. * Number of Simultaneous lights allowed on the material.
  34997. */
  34998. _this._maxSimultaneousLights = 4;
  34999. /**
  35000. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  35001. */
  35002. _this._invertNormalMapX = false;
  35003. /**
  35004. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  35005. */
  35006. _this._invertNormalMapY = false;
  35007. /**
  35008. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35009. */
  35010. _this._twoSidedLighting = false;
  35011. /**
  35012. * Defines the alpha limits in alpha test mode.
  35013. */
  35014. _this._alphaCutOff = 0.4;
  35015. /**
  35016. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  35017. */
  35018. _this._forceAlphaTest = false;
  35019. /**
  35020. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  35021. * And/Or occlude the blended part.
  35022. */
  35023. _this._useAlphaFresnel = false;
  35024. /**
  35025. * The transparency mode of the material.
  35026. */
  35027. _this._transparencyMode = null;
  35028. /**
  35029. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  35030. * from cos thetav and roughness:
  35031. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  35032. */
  35033. _this._environmentBRDFTexture = null;
  35034. /**
  35035. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  35036. */
  35037. _this._forceIrradianceInFragment = false;
  35038. /**
  35039. * Force normal to face away from face.
  35040. * (Temporary internal fix to remove before 3.1)
  35041. */
  35042. _this._forceNormalForward = false;
  35043. _this._renderTargets = new BABYLON.SmartArray(16);
  35044. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35045. // Setup the default processing configuration to the scene.
  35046. _this._attachImageProcessingConfiguration(null);
  35047. _this.getRenderTargetTextures = function () {
  35048. _this._renderTargets.reset();
  35049. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35050. _this._renderTargets.push(_this._reflectionTexture);
  35051. }
  35052. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35053. _this._renderTargets.push(_this._refractionTexture);
  35054. }
  35055. return _this._renderTargets;
  35056. };
  35057. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  35058. return _this;
  35059. }
  35060. /**
  35061. * Attaches a new image processing configuration to the PBR Material.
  35062. * @param configuration
  35063. */
  35064. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35065. var _this = this;
  35066. if (configuration === this._imageProcessingConfiguration) {
  35067. return;
  35068. }
  35069. // Detaches observer.
  35070. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35071. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35072. }
  35073. // Pick the scene configuration if needed.
  35074. if (!configuration) {
  35075. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35076. }
  35077. else {
  35078. this._imageProcessingConfiguration = configuration;
  35079. }
  35080. // Attaches observer.
  35081. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35082. _this._markAllSubMeshesAsImageProcessingDirty();
  35083. });
  35084. };
  35085. PBRBaseMaterial.prototype.getClassName = function () {
  35086. return "PBRBaseMaterial";
  35087. };
  35088. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  35089. get: function () {
  35090. return this._useLogarithmicDepth;
  35091. },
  35092. set: function (value) {
  35093. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35094. },
  35095. enumerable: true,
  35096. configurable: true
  35097. });
  35098. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  35099. /**
  35100. * Gets the current transparency mode.
  35101. */
  35102. get: function () {
  35103. return this._transparencyMode;
  35104. },
  35105. /**
  35106. * Sets the transparency mode of the material.
  35107. */
  35108. set: function (value) {
  35109. if (this._transparencyMode === value) {
  35110. return;
  35111. }
  35112. this._transparencyMode = value;
  35113. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  35114. this._markAllSubMeshesAsTexturesDirty();
  35115. },
  35116. enumerable: true,
  35117. configurable: true
  35118. });
  35119. /**
  35120. * Specifies whether or not the meshes using this material should be rendered in alpha blend mode.
  35121. */
  35122. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  35123. if (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35124. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST) {
  35125. return false;
  35126. }
  35127. return _super.prototype.needAlphaBlending.call(this);
  35128. };
  35129. /**
  35130. * Specifies whether or not the meshes using this material should be rendered in alpha blend mode.
  35131. */
  35132. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  35133. if (this._linkRefractionWithTransparency) {
  35134. return false;
  35135. }
  35136. if (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  35137. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST) {
  35138. return false;
  35139. }
  35140. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  35141. };
  35142. /**
  35143. * Specifies whether or not the meshes using this material should be rendered in alpha test mode.
  35144. */
  35145. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  35146. if (this._forceAlphaTest) {
  35147. return true;
  35148. }
  35149. if (this._linkRefractionWithTransparency) {
  35150. return false;
  35151. }
  35152. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  35153. };
  35154. /**
  35155. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  35156. */
  35157. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  35158. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35159. };
  35160. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  35161. return this._albedoTexture;
  35162. };
  35163. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35164. var _this = this;
  35165. if (subMesh.effect && this.isFrozen) {
  35166. if (this._wasPreviouslyReady) {
  35167. return true;
  35168. }
  35169. }
  35170. if (!subMesh._materialDefines) {
  35171. subMesh._materialDefines = new PBRMaterialDefines();
  35172. }
  35173. var scene = this.getScene();
  35174. var defines = subMesh._materialDefines;
  35175. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35176. if (defines._renderId === scene.getRenderId()) {
  35177. return true;
  35178. }
  35179. }
  35180. var engine = scene.getEngine();
  35181. // Lights
  35182. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35183. defines._needNormals = true;
  35184. // Textures
  35185. if (defines._areTexturesDirty) {
  35186. defines._needUVs = false;
  35187. if (scene.texturesEnabled) {
  35188. if (scene.getEngine().getCaps().textureLOD) {
  35189. defines.LODBASEDMICROSFURACE = true;
  35190. }
  35191. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35192. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  35193. return false;
  35194. }
  35195. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  35196. }
  35197. else {
  35198. defines.ALBEDO = false;
  35199. }
  35200. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35201. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35202. return false;
  35203. }
  35204. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35205. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  35206. }
  35207. else {
  35208. defines.AMBIENT = false;
  35209. }
  35210. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35211. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35212. return false;
  35213. }
  35214. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35215. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35216. }
  35217. else {
  35218. defines.OPACITY = false;
  35219. }
  35220. var reflectionTexture = this._getReflectionTexture();
  35221. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35222. if (!reflectionTexture.isReadyOrNotBlocking()) {
  35223. return false;
  35224. }
  35225. defines.REFLECTION = true;
  35226. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  35227. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  35228. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35229. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  35230. defines.INVERTCUBICMAP = true;
  35231. }
  35232. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  35233. switch (reflectionTexture.coordinatesMode) {
  35234. case BABYLON.Texture.CUBIC_MODE:
  35235. case BABYLON.Texture.INVCUBIC_MODE:
  35236. defines.REFLECTIONMAP_CUBIC = true;
  35237. break;
  35238. case BABYLON.Texture.EXPLICIT_MODE:
  35239. defines.REFLECTIONMAP_EXPLICIT = true;
  35240. break;
  35241. case BABYLON.Texture.PLANAR_MODE:
  35242. defines.REFLECTIONMAP_PLANAR = true;
  35243. break;
  35244. case BABYLON.Texture.PROJECTION_MODE:
  35245. defines.REFLECTIONMAP_PROJECTION = true;
  35246. break;
  35247. case BABYLON.Texture.SKYBOX_MODE:
  35248. defines.REFLECTIONMAP_SKYBOX = true;
  35249. break;
  35250. case BABYLON.Texture.SPHERICAL_MODE:
  35251. defines.REFLECTIONMAP_SPHERICAL = true;
  35252. break;
  35253. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35254. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  35255. break;
  35256. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35257. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  35258. break;
  35259. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35260. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  35261. break;
  35262. }
  35263. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  35264. if (reflectionTexture.sphericalPolynomial) {
  35265. defines.USESPHERICALFROMREFLECTIONMAP = true;
  35266. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  35267. defines.USESPHERICALINVERTEX = false;
  35268. }
  35269. else {
  35270. defines.USESPHERICALINVERTEX = true;
  35271. }
  35272. }
  35273. }
  35274. }
  35275. else {
  35276. defines.REFLECTION = false;
  35277. defines.REFLECTIONMAP_3D = false;
  35278. defines.REFLECTIONMAP_SPHERICAL = false;
  35279. defines.REFLECTIONMAP_PLANAR = false;
  35280. defines.REFLECTIONMAP_CUBIC = false;
  35281. defines.REFLECTIONMAP_PROJECTION = false;
  35282. defines.REFLECTIONMAP_SKYBOX = false;
  35283. defines.REFLECTIONMAP_EXPLICIT = false;
  35284. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35285. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35286. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35287. defines.INVERTCUBICMAP = false;
  35288. defines.USESPHERICALFROMREFLECTIONMAP = false;
  35289. defines.USESPHERICALINVERTEX = false;
  35290. defines.REFLECTIONMAP_OPPOSITEZ = false;
  35291. defines.LODINREFLECTIONALPHA = false;
  35292. defines.GAMMAREFLECTION = false;
  35293. }
  35294. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35295. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35296. return false;
  35297. }
  35298. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35299. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35300. }
  35301. else {
  35302. defines.LIGHTMAP = false;
  35303. }
  35304. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35305. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35306. return false;
  35307. }
  35308. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35309. }
  35310. else {
  35311. defines.EMISSIVE = false;
  35312. }
  35313. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35314. if (this._metallicTexture) {
  35315. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  35316. return false;
  35317. }
  35318. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  35319. defines.METALLICWORKFLOW = true;
  35320. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  35321. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  35322. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  35323. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  35324. }
  35325. else if (this._reflectivityTexture) {
  35326. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  35327. return false;
  35328. }
  35329. defines.METALLICWORKFLOW = false;
  35330. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  35331. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  35332. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  35333. }
  35334. else {
  35335. defines.METALLICWORKFLOW = false;
  35336. defines.REFLECTIVITY = false;
  35337. }
  35338. if (this._microSurfaceTexture) {
  35339. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  35340. return false;
  35341. }
  35342. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  35343. }
  35344. else {
  35345. defines.MICROSURFACEMAP = false;
  35346. }
  35347. }
  35348. else {
  35349. defines.REFLECTIVITY = false;
  35350. defines.MICROSURFACEMAP = false;
  35351. }
  35352. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35353. // Bump texure can not be none blocking.
  35354. if (!this._bumpTexture.isReady()) {
  35355. return false;
  35356. }
  35357. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35358. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35359. defines.PARALLAX = true;
  35360. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  35361. }
  35362. else {
  35363. defines.PARALLAX = false;
  35364. }
  35365. }
  35366. else {
  35367. defines.BUMP = false;
  35368. }
  35369. var refractionTexture = this._getRefractionTexture();
  35370. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35371. if (!refractionTexture.isReadyOrNotBlocking()) {
  35372. return false;
  35373. }
  35374. defines.REFRACTION = true;
  35375. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  35376. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  35377. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  35378. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  35379. if (this._linkRefractionWithTransparency) {
  35380. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  35381. }
  35382. }
  35383. else {
  35384. defines.REFRACTION = false;
  35385. }
  35386. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35387. // This is blocking.
  35388. if (!this._environmentBRDFTexture.isReady()) {
  35389. return false;
  35390. }
  35391. defines.ENVIRONMENTBRDF = true;
  35392. }
  35393. else {
  35394. defines.ENVIRONMENTBRDF = false;
  35395. }
  35396. if (this._shouldUseAlphaFromAlbedoTexture()) {
  35397. defines.ALPHAFROMALBEDO = true;
  35398. }
  35399. else {
  35400. defines.ALPHAFROMALBEDO = false;
  35401. }
  35402. }
  35403. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35404. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  35405. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  35406. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  35407. defines.METALLICWORKFLOW = true;
  35408. }
  35409. else {
  35410. defines.METALLICWORKFLOW = false;
  35411. }
  35412. if (!this.backFaceCulling && this._twoSidedLighting) {
  35413. defines.TWOSIDEDLIGHTING = true;
  35414. }
  35415. else {
  35416. defines.TWOSIDEDLIGHTING = false;
  35417. }
  35418. defines.ALPHATESTVALUE = this._alphaCutOff;
  35419. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35420. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  35421. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  35422. }
  35423. if (defines._areImageProcessingDirty) {
  35424. if (!this._imageProcessingConfiguration.isReady()) {
  35425. return false;
  35426. }
  35427. this._imageProcessingConfiguration.prepareDefines(defines);
  35428. }
  35429. defines.FORCENORMALFORWARD = this._forceNormalForward;
  35430. // Misc.
  35431. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35432. // Values that need to be evaluated on every frame
  35433. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  35434. // Attribs
  35435. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE)) {
  35436. if (mesh) {
  35437. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35438. mesh.createNormals(true);
  35439. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  35440. }
  35441. }
  35442. }
  35443. // Get correct effect
  35444. if (defines.isDirty) {
  35445. defines.markAsProcessed();
  35446. scene.resetCachedMaterial();
  35447. // Fallbacks
  35448. var fallbacks = new BABYLON.EffectFallbacks();
  35449. var fallbackRank = 0;
  35450. if (defines.USESPHERICALINVERTEX) {
  35451. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  35452. }
  35453. if (defines.FOG) {
  35454. fallbacks.addFallback(fallbackRank, "FOG");
  35455. }
  35456. if (defines.POINTSIZE) {
  35457. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  35458. }
  35459. if (defines.LOGARITHMICDEPTH) {
  35460. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  35461. }
  35462. if (defines.PARALLAX) {
  35463. fallbacks.addFallback(fallbackRank, "PARALLAX");
  35464. }
  35465. if (defines.PARALLAXOCCLUSION) {
  35466. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  35467. }
  35468. if (defines.ENVIRONMENTBRDF) {
  35469. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  35470. }
  35471. if (defines.TANGENT) {
  35472. fallbacks.addFallback(fallbackRank++, "TANGENT");
  35473. }
  35474. if (defines.BUMP) {
  35475. fallbacks.addFallback(fallbackRank++, "BUMP");
  35476. }
  35477. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  35478. if (defines.SPECULARTERM) {
  35479. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  35480. }
  35481. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  35482. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  35483. }
  35484. if (defines.LIGHTMAP) {
  35485. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  35486. }
  35487. if (defines.NORMAL) {
  35488. fallbacks.addFallback(fallbackRank++, "NORMAL");
  35489. }
  35490. if (defines.AMBIENT) {
  35491. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  35492. }
  35493. if (defines.EMISSIVE) {
  35494. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  35495. }
  35496. if (defines.VERTEXCOLOR) {
  35497. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  35498. }
  35499. if (defines.NUM_BONE_INFLUENCERS > 0) {
  35500. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  35501. }
  35502. if (defines.MORPHTARGETS) {
  35503. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  35504. }
  35505. //Attributes
  35506. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35507. if (defines.NORMAL) {
  35508. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35509. }
  35510. if (defines.TANGENT) {
  35511. attribs.push(BABYLON.VertexBuffer.TangentKind);
  35512. }
  35513. if (defines.UV1) {
  35514. attribs.push(BABYLON.VertexBuffer.UVKind);
  35515. }
  35516. if (defines.UV2) {
  35517. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35518. }
  35519. if (defines.VERTEXCOLOR) {
  35520. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35521. }
  35522. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35523. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35524. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35525. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  35526. "vFogInfos", "vFogColor", "pointSize",
  35527. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35528. "mBones",
  35529. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35530. "vLightingIntensity",
  35531. "logarithmicDepthConstant",
  35532. "vSphericalX", "vSphericalY", "vSphericalZ",
  35533. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  35534. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  35535. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  35536. "vTangentSpaceParams"
  35537. ];
  35538. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  35539. "bumpSampler", "lightmapSampler", "opacitySampler",
  35540. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  35541. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  35542. "microSurfaceSampler", "environmentBrdfSampler"];
  35543. var uniformBuffers = ["Material", "Scene"];
  35544. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35545. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35546. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35547. uniformsNames: uniforms,
  35548. uniformBuffersNames: uniformBuffers,
  35549. samplers: samplers,
  35550. defines: defines,
  35551. maxSimultaneousLights: this._maxSimultaneousLights
  35552. });
  35553. var onCompiled = function (effect) {
  35554. if (_this.onCompiled) {
  35555. _this.onCompiled(effect);
  35556. }
  35557. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  35558. };
  35559. var join = defines.toString();
  35560. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  35561. attributes: attribs,
  35562. uniformsNames: uniforms,
  35563. uniformBuffersNames: uniformBuffers,
  35564. samplers: samplers,
  35565. defines: join,
  35566. fallbacks: fallbacks,
  35567. onCompiled: onCompiled,
  35568. onError: this.onError,
  35569. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35570. }, engine), defines);
  35571. this.buildUniformLayout();
  35572. }
  35573. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35574. return false;
  35575. }
  35576. defines._renderId = scene.getRenderId();
  35577. this._wasPreviouslyReady = true;
  35578. return true;
  35579. };
  35580. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  35581. // Order is important !
  35582. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  35583. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  35584. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35585. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35586. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35587. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  35588. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  35589. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35590. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35591. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35592. this._uniformBuffer.addUniform("albedoMatrix", 16);
  35593. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35594. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35595. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35596. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35597. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  35598. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  35599. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35600. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35601. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35602. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35603. this._uniformBuffer.addUniform("vReflectionColor", 3);
  35604. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  35605. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  35606. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  35607. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  35608. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  35609. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35610. this._uniformBuffer.addUniform("pointSize", 1);
  35611. this._uniformBuffer.create();
  35612. };
  35613. PBRBaseMaterial.prototype.unbind = function () {
  35614. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35615. this._uniformBuffer.setTexture("reflectionSampler", null);
  35616. }
  35617. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35618. this._uniformBuffer.setTexture("refractionSampler", null);
  35619. }
  35620. _super.prototype.unbind.call(this);
  35621. };
  35622. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  35623. this._activeEffect.setMatrix("world", world);
  35624. };
  35625. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35626. var scene = this.getScene();
  35627. var defines = subMesh._materialDefines;
  35628. if (!defines) {
  35629. return;
  35630. }
  35631. var effect = subMesh.effect;
  35632. if (!effect) {
  35633. return;
  35634. }
  35635. this._activeEffect = effect;
  35636. // Matrices
  35637. this.bindOnlyWorldMatrix(world);
  35638. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35639. // Bones
  35640. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  35641. var reflectionTexture = null;
  35642. if (mustRebind) {
  35643. this._uniformBuffer.bindToEffect(effect, "Material");
  35644. this.bindViewProjection(effect);
  35645. reflectionTexture = this._getReflectionTexture();
  35646. var refractionTexture = this._getRefractionTexture();
  35647. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35648. // Texture uniforms
  35649. if (scene.texturesEnabled) {
  35650. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35651. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  35652. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  35653. }
  35654. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35655. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  35656. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35657. }
  35658. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35659. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35660. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35661. }
  35662. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35663. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  35664. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  35665. var polynomials = reflectionTexture.sphericalPolynomial;
  35666. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  35667. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  35668. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  35669. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  35670. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  35671. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  35672. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  35673. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  35674. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  35675. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  35676. }
  35677. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  35678. }
  35679. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35680. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35681. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35682. }
  35683. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35684. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35685. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35686. }
  35687. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35688. if (this._metallicTexture) {
  35689. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  35690. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  35691. }
  35692. else if (this._reflectivityTexture) {
  35693. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  35694. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  35695. }
  35696. if (this._microSurfaceTexture) {
  35697. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  35698. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  35699. }
  35700. }
  35701. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35702. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  35703. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35704. if (scene._mirroredCameraPosition) {
  35705. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35706. }
  35707. else {
  35708. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35709. }
  35710. }
  35711. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35712. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  35713. var depth = 1.0;
  35714. if (!refractionTexture.isCube) {
  35715. if (refractionTexture.depth) {
  35716. depth = refractionTexture.depth;
  35717. }
  35718. }
  35719. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  35720. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  35721. }
  35722. }
  35723. // Point size
  35724. if (this.pointsCloud) {
  35725. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35726. }
  35727. // Colors
  35728. if (defines.METALLICWORKFLOW) {
  35729. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  35730. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  35731. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  35732. }
  35733. else {
  35734. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  35735. }
  35736. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  35737. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  35738. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  35739. // Misc
  35740. this._lightingInfos.x = this._directIntensity;
  35741. this._lightingInfos.y = this._emissiveIntensity;
  35742. this._lightingInfos.z = this._environmentIntensity;
  35743. this._lightingInfos.w = this._specularIntensity;
  35744. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  35745. }
  35746. // Textures
  35747. if (scene.texturesEnabled) {
  35748. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  35749. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  35750. }
  35751. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  35752. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  35753. }
  35754. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  35755. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  35756. }
  35757. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  35758. if (defines.LODBASEDMICROSFURACE) {
  35759. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  35760. }
  35761. else {
  35762. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  35763. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  35764. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  35765. }
  35766. }
  35767. if (defines.ENVIRONMENTBRDF) {
  35768. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  35769. }
  35770. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  35771. if (defines.LODBASEDMICROSFURACE) {
  35772. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  35773. }
  35774. else {
  35775. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  35776. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  35777. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  35778. }
  35779. }
  35780. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  35781. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  35782. }
  35783. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  35784. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  35785. }
  35786. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  35787. if (this._metallicTexture) {
  35788. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  35789. }
  35790. else if (this._reflectivityTexture) {
  35791. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  35792. }
  35793. if (this._microSurfaceTexture) {
  35794. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  35795. }
  35796. }
  35797. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  35798. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  35799. }
  35800. }
  35801. // Clip plane
  35802. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  35803. // Colors
  35804. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  35805. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  35806. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  35807. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  35808. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35809. }
  35810. if (mustRebind || !this.isFrozen) {
  35811. // Lights
  35812. if (scene.lightsEnabled && !this._disableLighting) {
  35813. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  35814. }
  35815. // View
  35816. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  35817. this.bindView(effect);
  35818. }
  35819. // Fog
  35820. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  35821. // Morph targets
  35822. if (defines.NUM_MORPH_INFLUENCERS) {
  35823. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  35824. }
  35825. // image processing
  35826. this._imageProcessingConfiguration.bind(this._activeEffect);
  35827. // Log. depth
  35828. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  35829. }
  35830. this._uniformBuffer.update();
  35831. this._afterBind(mesh);
  35832. };
  35833. PBRBaseMaterial.prototype.getAnimatables = function () {
  35834. var results = [];
  35835. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  35836. results.push(this._albedoTexture);
  35837. }
  35838. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35839. results.push(this._ambientTexture);
  35840. }
  35841. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35842. results.push(this._opacityTexture);
  35843. }
  35844. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35845. results.push(this._reflectionTexture);
  35846. }
  35847. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35848. results.push(this._emissiveTexture);
  35849. }
  35850. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  35851. results.push(this._metallicTexture);
  35852. }
  35853. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  35854. results.push(this._reflectivityTexture);
  35855. }
  35856. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35857. results.push(this._bumpTexture);
  35858. }
  35859. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35860. results.push(this._lightmapTexture);
  35861. }
  35862. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35863. results.push(this._refractionTexture);
  35864. }
  35865. return results;
  35866. };
  35867. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  35868. if (this._reflectionTexture) {
  35869. return this._reflectionTexture;
  35870. }
  35871. return this.getScene().environmentTexture;
  35872. };
  35873. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  35874. if (this._refractionTexture) {
  35875. return this._refractionTexture;
  35876. }
  35877. if (this._linkRefractionWithTransparency) {
  35878. return this.getScene().environmentTexture;
  35879. }
  35880. return null;
  35881. };
  35882. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35883. if (forceDisposeTextures) {
  35884. if (this._albedoTexture) {
  35885. this._albedoTexture.dispose();
  35886. }
  35887. if (this._ambientTexture) {
  35888. this._ambientTexture.dispose();
  35889. }
  35890. if (this._opacityTexture) {
  35891. this._opacityTexture.dispose();
  35892. }
  35893. if (this._reflectionTexture) {
  35894. this._reflectionTexture.dispose();
  35895. }
  35896. if (this._environmentBRDFTexture) {
  35897. this._environmentBRDFTexture.dispose();
  35898. }
  35899. if (this._emissiveTexture) {
  35900. this._emissiveTexture.dispose();
  35901. }
  35902. if (this._metallicTexture) {
  35903. this._metallicTexture.dispose();
  35904. }
  35905. if (this._reflectivityTexture) {
  35906. this._reflectivityTexture.dispose();
  35907. }
  35908. if (this._bumpTexture) {
  35909. this._bumpTexture.dispose();
  35910. }
  35911. if (this._lightmapTexture) {
  35912. this._lightmapTexture.dispose();
  35913. }
  35914. if (this._refractionTexture) {
  35915. this._refractionTexture.dispose();
  35916. }
  35917. }
  35918. this._renderTargets.dispose();
  35919. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35920. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35921. }
  35922. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35923. };
  35924. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  35925. __decorate([
  35926. BABYLON.serializeAsImageProcessingConfiguration()
  35927. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  35928. __decorate([
  35929. BABYLON.serialize()
  35930. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  35931. __decorate([
  35932. BABYLON.serialize()
  35933. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  35934. return PBRBaseMaterial;
  35935. }(BABYLON.PushMaterial));
  35936. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  35937. })(BABYLON || (BABYLON = {}));
  35938. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  35939. var BABYLON;
  35940. (function (BABYLON) {
  35941. var Internals;
  35942. (function (Internals) {
  35943. /**
  35944. * The Physically based simple base material of BJS.
  35945. *
  35946. * This enables better naming and convention enforcements on top of the pbrMaterial.
  35947. * It is used as the base class for both the specGloss and metalRough conventions.
  35948. */
  35949. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  35950. __extends(PBRBaseSimpleMaterial, _super);
  35951. /**
  35952. * Instantiates a new PBRMaterial instance.
  35953. *
  35954. * @param name The material name
  35955. * @param scene The scene the material will be use in.
  35956. */
  35957. function PBRBaseSimpleMaterial(name, scene) {
  35958. var _this = _super.call(this, name, scene) || this;
  35959. /**
  35960. * Number of Simultaneous lights allowed on the material.
  35961. */
  35962. _this.maxSimultaneousLights = 4;
  35963. /**
  35964. * If sets to true, disables all the lights affecting the material.
  35965. */
  35966. _this.disableLighting = false;
  35967. /**
  35968. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35969. */
  35970. _this.invertNormalMapX = false;
  35971. /**
  35972. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35973. */
  35974. _this.invertNormalMapY = false;
  35975. /**
  35976. * Emissivie color used to self-illuminate the model.
  35977. */
  35978. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35979. /**
  35980. * Occlusion Channel Strenght.
  35981. */
  35982. _this.occlusionStrength = 1.0;
  35983. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  35984. _this._useAlphaFromAlbedoTexture = true;
  35985. _this._useAmbientInGrayScale = true;
  35986. return _this;
  35987. }
  35988. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  35989. /**
  35990. * Gets the current double sided mode.
  35991. */
  35992. get: function () {
  35993. return this._twoSidedLighting;
  35994. },
  35995. /**
  35996. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35997. */
  35998. set: function (value) {
  35999. if (this._twoSidedLighting === value) {
  36000. return;
  36001. }
  36002. this._twoSidedLighting = value;
  36003. this.backFaceCulling = !value;
  36004. this._markAllSubMeshesAsTexturesDirty();
  36005. },
  36006. enumerable: true,
  36007. configurable: true
  36008. });
  36009. /**
  36010. * Return the active textures of the material.
  36011. */
  36012. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  36013. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36014. if (this.environmentTexture) {
  36015. activeTextures.push(this.environmentTexture);
  36016. }
  36017. if (this.normalTexture) {
  36018. activeTextures.push(this.normalTexture);
  36019. }
  36020. if (this.emissiveTexture) {
  36021. activeTextures.push(this.emissiveTexture);
  36022. }
  36023. if (this.occlusionTexture) {
  36024. activeTextures.push(this.occlusionTexture);
  36025. }
  36026. return activeTextures;
  36027. };
  36028. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  36029. return "PBRBaseSimpleMaterial";
  36030. };
  36031. __decorate([
  36032. BABYLON.serialize(),
  36033. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36034. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  36035. __decorate([
  36036. BABYLON.serialize(),
  36037. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36038. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  36039. __decorate([
  36040. BABYLON.serializeAsTexture(),
  36041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  36042. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  36043. __decorate([
  36044. BABYLON.serialize(),
  36045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36046. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  36047. __decorate([
  36048. BABYLON.serialize(),
  36049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36050. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  36051. __decorate([
  36052. BABYLON.serializeAsTexture(),
  36053. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  36054. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  36055. __decorate([
  36056. BABYLON.serializeAsColor3("emissive"),
  36057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36058. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  36059. __decorate([
  36060. BABYLON.serializeAsTexture(),
  36061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36062. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  36063. __decorate([
  36064. BABYLON.serialize(),
  36065. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  36066. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  36067. __decorate([
  36068. BABYLON.serializeAsTexture(),
  36069. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  36070. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  36071. __decorate([
  36072. BABYLON.serialize(),
  36073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  36074. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  36075. __decorate([
  36076. BABYLON.serialize()
  36077. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  36078. return PBRBaseSimpleMaterial;
  36079. }(BABYLON.PBRBaseMaterial));
  36080. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  36081. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  36082. })(BABYLON || (BABYLON = {}));
  36083. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  36084. var BABYLON;
  36085. (function (BABYLON) {
  36086. /**
  36087. * The Physically based material of BJS.
  36088. *
  36089. * This offers the main features of a standard PBR material.
  36090. * For more information, please refer to the documentation :
  36091. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36092. */
  36093. var PBRMaterial = /** @class */ (function (_super) {
  36094. __extends(PBRMaterial, _super);
  36095. /**
  36096. * Instantiates a new PBRMaterial instance.
  36097. *
  36098. * @param name The material name
  36099. * @param scene The scene the material will be use in.
  36100. */
  36101. function PBRMaterial(name, scene) {
  36102. var _this = _super.call(this, name, scene) || this;
  36103. /**
  36104. * Intensity of the direct lights e.g. the four lights available in your scene.
  36105. * This impacts both the direct diffuse and specular highlights.
  36106. */
  36107. _this.directIntensity = 1.0;
  36108. /**
  36109. * Intensity of the emissive part of the material.
  36110. * This helps controlling the emissive effect without modifying the emissive color.
  36111. */
  36112. _this.emissiveIntensity = 1.0;
  36113. /**
  36114. * Intensity of the environment e.g. how much the environment will light the object
  36115. * either through harmonics for rough material or through the refelction for shiny ones.
  36116. */
  36117. _this.environmentIntensity = 1.0;
  36118. /**
  36119. * This is a special control allowing the reduction of the specular highlights coming from the
  36120. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36121. */
  36122. _this.specularIntensity = 1.0;
  36123. /**
  36124. * Debug Control allowing disabling the bump map on this material.
  36125. */
  36126. _this.disableBumpMap = false;
  36127. /**
  36128. * AKA Occlusion Texture Intensity in other nomenclature.
  36129. */
  36130. _this.ambientTextureStrength = 1.0;
  36131. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  36132. /**
  36133. * AKA Diffuse Color in other nomenclature.
  36134. */
  36135. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  36136. /**
  36137. * AKA Specular Color in other nomenclature.
  36138. */
  36139. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36140. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  36141. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  36142. /**
  36143. * AKA Glossiness in other nomenclature.
  36144. */
  36145. _this.microSurface = 1.0;
  36146. /**
  36147. * source material index of refraction (IOR)' / 'destination material IOR.
  36148. */
  36149. _this.indexOfRefraction = 0.66;
  36150. /**
  36151. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36152. */
  36153. _this.invertRefractionY = false;
  36154. /**
  36155. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36156. * Materials half opaque for instance using refraction could benefit from this control.
  36157. */
  36158. _this.linkRefractionWithTransparency = false;
  36159. _this.useLightmapAsShadowmap = false;
  36160. /**
  36161. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36162. */
  36163. _this.useAlphaFromAlbedoTexture = false;
  36164. /**
  36165. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36166. */
  36167. _this.forceAlphaTest = false;
  36168. /**
  36169. * Defines the alpha limits in alpha test mode.
  36170. */
  36171. _this.alphaCutOff = 0.4;
  36172. /**
  36173. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36174. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36175. */
  36176. _this.useSpecularOverAlpha = true;
  36177. /**
  36178. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36179. */
  36180. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  36181. /**
  36182. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36183. */
  36184. _this.useRoughnessFromMetallicTextureAlpha = true;
  36185. /**
  36186. * Specifies if the metallic texture contains the roughness information in its green channel.
  36187. */
  36188. _this.useRoughnessFromMetallicTextureGreen = false;
  36189. /**
  36190. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36191. */
  36192. _this.useMetallnessFromMetallicTextureBlue = false;
  36193. /**
  36194. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36195. */
  36196. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  36197. /**
  36198. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36199. */
  36200. _this.useAmbientInGrayScale = false;
  36201. /**
  36202. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36203. * The material will try to infer what glossiness each pixel should be.
  36204. */
  36205. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  36206. /**
  36207. * BJS is using an harcoded light falloff based on a manually sets up range.
  36208. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36209. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36210. */
  36211. _this.usePhysicalLightFalloff = true;
  36212. /**
  36213. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36214. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36215. */
  36216. _this.useRadianceOverAlpha = true;
  36217. /**
  36218. * Allows using the bump map in parallax mode.
  36219. */
  36220. _this.useParallax = false;
  36221. /**
  36222. * Allows using the bump map in parallax occlusion mode.
  36223. */
  36224. _this.useParallaxOcclusion = false;
  36225. /**
  36226. * Controls the scale bias of the parallax mode.
  36227. */
  36228. _this.parallaxScaleBias = 0.05;
  36229. /**
  36230. * If sets to true, disables all the lights affecting the material.
  36231. */
  36232. _this.disableLighting = false;
  36233. /**
  36234. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36235. */
  36236. _this.forceIrradianceInFragment = false;
  36237. /**
  36238. * Number of Simultaneous lights allowed on the material.
  36239. */
  36240. _this.maxSimultaneousLights = 4;
  36241. /**
  36242. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  36243. */
  36244. _this.invertNormalMapX = false;
  36245. /**
  36246. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  36247. */
  36248. _this.invertNormalMapY = false;
  36249. /**
  36250. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36251. */
  36252. _this.twoSidedLighting = false;
  36253. /**
  36254. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36255. * And/Or occlude the blended part.
  36256. */
  36257. _this.useAlphaFresnel = false;
  36258. /**
  36259. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36260. * And/Or occlude the blended part.
  36261. */
  36262. _this.environmentBRDFTexture = null;
  36263. /**
  36264. * Force normal to face away from face.
  36265. * (Temporary internal fix to remove before 3.1)
  36266. */
  36267. _this.forceNormalForward = false;
  36268. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36269. return _this;
  36270. }
  36271. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  36272. /**
  36273. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  36274. */
  36275. get: function () {
  36276. return this._PBRMATERIAL_OPAQUE;
  36277. },
  36278. enumerable: true,
  36279. configurable: true
  36280. });
  36281. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  36282. /**
  36283. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  36284. */
  36285. get: function () {
  36286. return this._PBRMATERIAL_ALPHATEST;
  36287. },
  36288. enumerable: true,
  36289. configurable: true
  36290. });
  36291. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  36292. /**
  36293. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36294. */
  36295. get: function () {
  36296. return this._PBRMATERIAL_ALPHABLEND;
  36297. },
  36298. enumerable: true,
  36299. configurable: true
  36300. });
  36301. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  36302. /**
  36303. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  36304. * They are also discarded below the alpha cutoff threshold to improve performances.
  36305. */
  36306. get: function () {
  36307. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  36308. },
  36309. enumerable: true,
  36310. configurable: true
  36311. });
  36312. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  36313. /**
  36314. * Gets the image processing configuration used either in this material.
  36315. */
  36316. get: function () {
  36317. return this._imageProcessingConfiguration;
  36318. },
  36319. /**
  36320. * Sets the Default image processing configuration used either in the this material.
  36321. *
  36322. * If sets to null, the scene one is in use.
  36323. */
  36324. set: function (value) {
  36325. this._attachImageProcessingConfiguration(value);
  36326. // Ensure the effect will be rebuilt.
  36327. this._markAllSubMeshesAsTexturesDirty();
  36328. },
  36329. enumerable: true,
  36330. configurable: true
  36331. });
  36332. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  36333. /**
  36334. * Gets wether the color curves effect is enabled.
  36335. */
  36336. get: function () {
  36337. return this.imageProcessingConfiguration.colorCurvesEnabled;
  36338. },
  36339. /**
  36340. * Sets wether the color curves effect is enabled.
  36341. */
  36342. set: function (value) {
  36343. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  36344. },
  36345. enumerable: true,
  36346. configurable: true
  36347. });
  36348. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  36349. /**
  36350. * Gets wether the color grading effect is enabled.
  36351. */
  36352. get: function () {
  36353. return this.imageProcessingConfiguration.colorGradingEnabled;
  36354. },
  36355. /**
  36356. * Gets wether the color grading effect is enabled.
  36357. */
  36358. set: function (value) {
  36359. this.imageProcessingConfiguration.colorGradingEnabled = value;
  36360. },
  36361. enumerable: true,
  36362. configurable: true
  36363. });
  36364. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  36365. /**
  36366. * Gets wether tonemapping is enabled or not.
  36367. */
  36368. get: function () {
  36369. return this._imageProcessingConfiguration.toneMappingEnabled;
  36370. },
  36371. /**
  36372. * Sets wether tonemapping is enabled or not
  36373. */
  36374. set: function (value) {
  36375. this._imageProcessingConfiguration.toneMappingEnabled = value;
  36376. },
  36377. enumerable: true,
  36378. configurable: true
  36379. });
  36380. ;
  36381. ;
  36382. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  36383. /**
  36384. * The camera exposure used on this material.
  36385. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36386. * This corresponds to a photographic exposure.
  36387. */
  36388. get: function () {
  36389. return this._imageProcessingConfiguration.exposure;
  36390. },
  36391. /**
  36392. * The camera exposure used on this material.
  36393. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  36394. * This corresponds to a photographic exposure.
  36395. */
  36396. set: function (value) {
  36397. this._imageProcessingConfiguration.exposure = value;
  36398. },
  36399. enumerable: true,
  36400. configurable: true
  36401. });
  36402. ;
  36403. ;
  36404. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  36405. /**
  36406. * Gets The camera contrast used on this material.
  36407. */
  36408. get: function () {
  36409. return this._imageProcessingConfiguration.contrast;
  36410. },
  36411. /**
  36412. * Sets The camera contrast used on this material.
  36413. */
  36414. set: function (value) {
  36415. this._imageProcessingConfiguration.contrast = value;
  36416. },
  36417. enumerable: true,
  36418. configurable: true
  36419. });
  36420. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  36421. /**
  36422. * Gets the Color Grading 2D Lookup Texture.
  36423. */
  36424. get: function () {
  36425. return this._imageProcessingConfiguration.colorGradingTexture;
  36426. },
  36427. /**
  36428. * Sets the Color Grading 2D Lookup Texture.
  36429. */
  36430. set: function (value) {
  36431. this._imageProcessingConfiguration.colorGradingTexture = value;
  36432. },
  36433. enumerable: true,
  36434. configurable: true
  36435. });
  36436. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  36437. /**
  36438. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36439. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36440. * 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;
  36441. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36442. */
  36443. get: function () {
  36444. return this._imageProcessingConfiguration.colorCurves;
  36445. },
  36446. /**
  36447. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  36448. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  36449. * 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;
  36450. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  36451. */
  36452. set: function (value) {
  36453. this._imageProcessingConfiguration.colorCurves = value;
  36454. },
  36455. enumerable: true,
  36456. configurable: true
  36457. });
  36458. PBRMaterial.prototype.getClassName = function () {
  36459. return "PBRMaterial";
  36460. };
  36461. PBRMaterial.prototype.getActiveTextures = function () {
  36462. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36463. if (this._albedoTexture) {
  36464. activeTextures.push(this._albedoTexture);
  36465. }
  36466. if (this._ambientTexture) {
  36467. activeTextures.push(this._ambientTexture);
  36468. }
  36469. if (this._opacityTexture) {
  36470. activeTextures.push(this._opacityTexture);
  36471. }
  36472. if (this._reflectionTexture) {
  36473. activeTextures.push(this._reflectionTexture);
  36474. }
  36475. if (this._emissiveTexture) {
  36476. activeTextures.push(this._emissiveTexture);
  36477. }
  36478. if (this._reflectivityTexture) {
  36479. activeTextures.push(this._reflectivityTexture);
  36480. }
  36481. if (this._metallicTexture) {
  36482. activeTextures.push(this._metallicTexture);
  36483. }
  36484. if (this._microSurfaceTexture) {
  36485. activeTextures.push(this._microSurfaceTexture);
  36486. }
  36487. if (this._bumpTexture) {
  36488. activeTextures.push(this._bumpTexture);
  36489. }
  36490. if (this._lightmapTexture) {
  36491. activeTextures.push(this._lightmapTexture);
  36492. }
  36493. if (this._refractionTexture) {
  36494. activeTextures.push(this._refractionTexture);
  36495. }
  36496. return activeTextures;
  36497. };
  36498. PBRMaterial.prototype.hasTexture = function (texture) {
  36499. if (_super.prototype.hasTexture.call(this, texture)) {
  36500. return true;
  36501. }
  36502. if (this._albedoTexture === texture) {
  36503. return true;
  36504. }
  36505. if (this._ambientTexture === texture) {
  36506. return true;
  36507. }
  36508. if (this._opacityTexture === texture) {
  36509. return true;
  36510. }
  36511. if (this._reflectionTexture === texture) {
  36512. return true;
  36513. }
  36514. if (this._reflectivityTexture === texture) {
  36515. return true;
  36516. }
  36517. if (this._metallicTexture === texture) {
  36518. return true;
  36519. }
  36520. if (this._microSurfaceTexture === texture) {
  36521. return true;
  36522. }
  36523. if (this._bumpTexture === texture) {
  36524. return true;
  36525. }
  36526. if (this._lightmapTexture === texture) {
  36527. return true;
  36528. }
  36529. if (this._refractionTexture === texture) {
  36530. return true;
  36531. }
  36532. return false;
  36533. };
  36534. PBRMaterial.prototype.clone = function (name) {
  36535. var _this = this;
  36536. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  36537. clone.id = name;
  36538. clone.name = name;
  36539. return clone;
  36540. };
  36541. PBRMaterial.prototype.serialize = function () {
  36542. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36543. serializationObject.customType = "BABYLON.PBRMaterial";
  36544. return serializationObject;
  36545. };
  36546. // Statics
  36547. PBRMaterial.Parse = function (source, scene, rootUrl) {
  36548. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  36549. };
  36550. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  36551. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  36552. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  36553. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  36554. __decorate([
  36555. BABYLON.serialize(),
  36556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36557. ], PBRMaterial.prototype, "directIntensity", void 0);
  36558. __decorate([
  36559. BABYLON.serialize(),
  36560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36561. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  36562. __decorate([
  36563. BABYLON.serialize(),
  36564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36565. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  36566. __decorate([
  36567. BABYLON.serialize(),
  36568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36569. ], PBRMaterial.prototype, "specularIntensity", void 0);
  36570. __decorate([
  36571. BABYLON.serialize(),
  36572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36573. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  36574. __decorate([
  36575. BABYLON.serializeAsTexture(),
  36576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36577. ], PBRMaterial.prototype, "albedoTexture", void 0);
  36578. __decorate([
  36579. BABYLON.serializeAsTexture(),
  36580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36581. ], PBRMaterial.prototype, "ambientTexture", void 0);
  36582. __decorate([
  36583. BABYLON.serialize(),
  36584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36585. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  36586. __decorate([
  36587. BABYLON.serializeAsTexture(),
  36588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36589. ], PBRMaterial.prototype, "opacityTexture", void 0);
  36590. __decorate([
  36591. BABYLON.serializeAsTexture(),
  36592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36593. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  36594. __decorate([
  36595. BABYLON.serializeAsTexture(),
  36596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36597. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  36598. __decorate([
  36599. BABYLON.serializeAsTexture(),
  36600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36601. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  36602. __decorate([
  36603. BABYLON.serializeAsTexture(),
  36604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36605. ], PBRMaterial.prototype, "metallicTexture", void 0);
  36606. __decorate([
  36607. BABYLON.serialize(),
  36608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36609. ], PBRMaterial.prototype, "metallic", void 0);
  36610. __decorate([
  36611. BABYLON.serialize(),
  36612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36613. ], PBRMaterial.prototype, "roughness", void 0);
  36614. __decorate([
  36615. BABYLON.serializeAsTexture(),
  36616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36617. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  36618. __decorate([
  36619. BABYLON.serializeAsTexture(),
  36620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36621. ], PBRMaterial.prototype, "bumpTexture", void 0);
  36622. __decorate([
  36623. BABYLON.serializeAsTexture(),
  36624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  36625. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  36626. __decorate([
  36627. BABYLON.serializeAsTexture(),
  36628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36629. ], PBRMaterial.prototype, "refractionTexture", void 0);
  36630. __decorate([
  36631. BABYLON.serializeAsColor3("ambient"),
  36632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36633. ], PBRMaterial.prototype, "ambientColor", void 0);
  36634. __decorate([
  36635. BABYLON.serializeAsColor3("albedo"),
  36636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36637. ], PBRMaterial.prototype, "albedoColor", void 0);
  36638. __decorate([
  36639. BABYLON.serializeAsColor3("reflectivity"),
  36640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36641. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  36642. __decorate([
  36643. BABYLON.serializeAsColor3("reflection"),
  36644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36645. ], PBRMaterial.prototype, "reflectionColor", void 0);
  36646. __decorate([
  36647. BABYLON.serializeAsColor3("emissive"),
  36648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36649. ], PBRMaterial.prototype, "emissiveColor", void 0);
  36650. __decorate([
  36651. BABYLON.serialize(),
  36652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36653. ], PBRMaterial.prototype, "microSurface", void 0);
  36654. __decorate([
  36655. BABYLON.serialize(),
  36656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36657. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  36658. __decorate([
  36659. BABYLON.serialize(),
  36660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36661. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  36662. __decorate([
  36663. BABYLON.serialize(),
  36664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36665. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  36666. __decorate([
  36667. BABYLON.serialize(),
  36668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36669. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36670. __decorate([
  36671. BABYLON.serialize(),
  36672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36673. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  36674. __decorate([
  36675. BABYLON.serialize(),
  36676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36677. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  36678. __decorate([
  36679. BABYLON.serialize(),
  36680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36681. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  36682. __decorate([
  36683. BABYLON.serialize(),
  36684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36685. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  36686. __decorate([
  36687. BABYLON.serialize(),
  36688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36689. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  36690. __decorate([
  36691. BABYLON.serialize(),
  36692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36693. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  36694. __decorate([
  36695. BABYLON.serialize(),
  36696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36697. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  36698. __decorate([
  36699. BABYLON.serialize(),
  36700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36701. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  36702. __decorate([
  36703. BABYLON.serialize(),
  36704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36705. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  36706. __decorate([
  36707. BABYLON.serialize(),
  36708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36709. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  36710. __decorate([
  36711. BABYLON.serialize(),
  36712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36713. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  36714. __decorate([
  36715. BABYLON.serialize(),
  36716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36717. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  36718. __decorate([
  36719. BABYLON.serialize(),
  36720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36721. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  36722. __decorate([
  36723. BABYLON.serialize(),
  36724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36725. ], PBRMaterial.prototype, "useParallax", void 0);
  36726. __decorate([
  36727. BABYLON.serialize(),
  36728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36729. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  36730. __decorate([
  36731. BABYLON.serialize(),
  36732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36733. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  36734. __decorate([
  36735. BABYLON.serialize(),
  36736. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36737. ], PBRMaterial.prototype, "disableLighting", void 0);
  36738. __decorate([
  36739. BABYLON.serialize(),
  36740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36741. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  36742. __decorate([
  36743. BABYLON.serialize(),
  36744. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36745. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  36746. __decorate([
  36747. BABYLON.serialize(),
  36748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36749. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  36750. __decorate([
  36751. BABYLON.serialize(),
  36752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36753. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  36754. __decorate([
  36755. BABYLON.serialize(),
  36756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36757. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  36758. __decorate([
  36759. BABYLON.serialize(),
  36760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36761. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  36762. __decorate([
  36763. BABYLON.serializeAsTexture(),
  36764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36765. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  36766. __decorate([
  36767. BABYLON.serialize(),
  36768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36769. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  36770. return PBRMaterial;
  36771. }(BABYLON.PBRBaseMaterial));
  36772. BABYLON.PBRMaterial = PBRMaterial;
  36773. })(BABYLON || (BABYLON = {}));
  36774. //# sourceMappingURL=babylon.pbrMaterial.js.map
  36775. var BABYLON;
  36776. (function (BABYLON) {
  36777. /**
  36778. * The PBR material of BJS following the metal roughness convention.
  36779. *
  36780. * This fits to the PBR convention in the GLTF definition:
  36781. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  36782. */
  36783. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  36784. __extends(PBRMetallicRoughnessMaterial, _super);
  36785. /**
  36786. * Instantiates a new PBRMetalRoughnessMaterial instance.
  36787. *
  36788. * @param name The material name
  36789. * @param scene The scene the material will be use in.
  36790. */
  36791. function PBRMetallicRoughnessMaterial(name, scene) {
  36792. var _this = _super.call(this, name, scene) || this;
  36793. _this._useRoughnessFromMetallicTextureAlpha = false;
  36794. _this._useRoughnessFromMetallicTextureGreen = true;
  36795. _this._useMetallnessFromMetallicTextureBlue = true;
  36796. return _this;
  36797. }
  36798. /**
  36799. * Return the currrent class name of the material.
  36800. */
  36801. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  36802. return "PBRMetallicRoughnessMaterial";
  36803. };
  36804. /**
  36805. * Return the active textures of the material.
  36806. */
  36807. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  36808. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36809. if (this.baseTexture) {
  36810. activeTextures.push(this.baseTexture);
  36811. }
  36812. if (this.metallicRoughnessTexture) {
  36813. activeTextures.push(this.metallicRoughnessTexture);
  36814. }
  36815. return activeTextures;
  36816. };
  36817. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  36818. if (_super.prototype.hasTexture.call(this, texture)) {
  36819. return true;
  36820. }
  36821. if (this.baseTexture === texture) {
  36822. return true;
  36823. }
  36824. if (this.metallicRoughnessTexture === texture) {
  36825. return true;
  36826. }
  36827. return false;
  36828. };
  36829. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  36830. var _this = this;
  36831. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  36832. clone.id = name;
  36833. clone.name = name;
  36834. return clone;
  36835. };
  36836. /**
  36837. * Serialize the material to a parsable JSON object.
  36838. */
  36839. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  36840. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36841. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  36842. return serializationObject;
  36843. };
  36844. /**
  36845. * Parses a JSON object correponding to the serialize function.
  36846. */
  36847. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  36848. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  36849. };
  36850. __decorate([
  36851. BABYLON.serializeAsColor3(),
  36852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36853. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  36854. __decorate([
  36855. BABYLON.serializeAsTexture(),
  36856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36857. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  36858. __decorate([
  36859. BABYLON.serialize(),
  36860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36861. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  36862. __decorate([
  36863. BABYLON.serialize(),
  36864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36865. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  36866. __decorate([
  36867. BABYLON.serializeAsTexture(),
  36868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  36869. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  36870. return PBRMetallicRoughnessMaterial;
  36871. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36872. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  36873. })(BABYLON || (BABYLON = {}));
  36874. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  36875. var BABYLON;
  36876. (function (BABYLON) {
  36877. /**
  36878. * The PBR material of BJS following the specular glossiness convention.
  36879. *
  36880. * This fits to the PBR convention in the GLTF definition:
  36881. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  36882. */
  36883. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  36884. __extends(PBRSpecularGlossinessMaterial, _super);
  36885. /**
  36886. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  36887. *
  36888. * @param name The material name
  36889. * @param scene The scene the material will be use in.
  36890. */
  36891. function PBRSpecularGlossinessMaterial(name, scene) {
  36892. var _this = _super.call(this, name, scene) || this;
  36893. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  36894. return _this;
  36895. }
  36896. /**
  36897. * Return the currrent class name of the material.
  36898. */
  36899. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  36900. return "PBRSpecularGlossinessMaterial";
  36901. };
  36902. /**
  36903. * Return the active textures of the material.
  36904. */
  36905. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  36906. var activeTextures = _super.prototype.getActiveTextures.call(this);
  36907. if (this.diffuseTexture) {
  36908. activeTextures.push(this.diffuseTexture);
  36909. }
  36910. if (this.specularGlossinessTexture) {
  36911. activeTextures.push(this.specularGlossinessTexture);
  36912. }
  36913. return activeTextures;
  36914. };
  36915. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  36916. if (_super.prototype.hasTexture.call(this, texture)) {
  36917. return true;
  36918. }
  36919. if (this.diffuseTexture === texture) {
  36920. return true;
  36921. }
  36922. if (this.specularGlossinessTexture === texture) {
  36923. return true;
  36924. }
  36925. return false;
  36926. };
  36927. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  36928. var _this = this;
  36929. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  36930. clone.id = name;
  36931. clone.name = name;
  36932. return clone;
  36933. };
  36934. /**
  36935. * Serialize the material to a parsable JSON object.
  36936. */
  36937. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  36938. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  36939. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  36940. return serializationObject;
  36941. };
  36942. /**
  36943. * Parses a JSON object correponding to the serialize function.
  36944. */
  36945. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  36946. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  36947. };
  36948. __decorate([
  36949. BABYLON.serializeAsColor3("diffuse"),
  36950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  36951. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  36952. __decorate([
  36953. BABYLON.serializeAsTexture(),
  36954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  36955. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  36956. __decorate([
  36957. BABYLON.serializeAsColor3("specular"),
  36958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  36959. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  36960. __decorate([
  36961. BABYLON.serialize(),
  36962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  36963. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  36964. __decorate([
  36965. BABYLON.serializeAsTexture(),
  36966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  36967. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  36968. return PBRSpecularGlossinessMaterial;
  36969. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  36970. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  36971. })(BABYLON || (BABYLON = {}));
  36972. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  36973. var BABYLON;
  36974. (function (BABYLON) {
  36975. BABYLON.CameraInputTypes = {};
  36976. var CameraInputsManager = /** @class */ (function () {
  36977. function CameraInputsManager(camera) {
  36978. this.attached = {};
  36979. this.camera = camera;
  36980. this.checkInputs = function () { };
  36981. }
  36982. CameraInputsManager.prototype.add = function (input) {
  36983. var type = input.getSimpleName();
  36984. if (this.attached[type]) {
  36985. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  36986. return;
  36987. }
  36988. this.attached[type] = input;
  36989. input.camera = this.camera;
  36990. //for checkInputs, we are dynamically creating a function
  36991. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  36992. if (input.checkInputs) {
  36993. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  36994. }
  36995. if (this.attachedElement) {
  36996. input.attachControl(this.attachedElement);
  36997. }
  36998. };
  36999. CameraInputsManager.prototype.remove = function (inputToRemove) {
  37000. for (var cam in this.attached) {
  37001. var input = this.attached[cam];
  37002. if (input === inputToRemove) {
  37003. input.detachControl(this.attachedElement);
  37004. input.camera = null;
  37005. delete this.attached[cam];
  37006. this.rebuildInputCheck();
  37007. }
  37008. }
  37009. };
  37010. CameraInputsManager.prototype.removeByType = function (inputType) {
  37011. for (var cam in this.attached) {
  37012. var input = this.attached[cam];
  37013. if (input.getClassName() === inputType) {
  37014. input.detachControl(this.attachedElement);
  37015. input.camera = null;
  37016. delete this.attached[cam];
  37017. this.rebuildInputCheck();
  37018. }
  37019. }
  37020. };
  37021. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  37022. var current = this.checkInputs;
  37023. return function () {
  37024. current();
  37025. fn();
  37026. };
  37027. };
  37028. CameraInputsManager.prototype.attachInput = function (input) {
  37029. if (this.attachedElement) {
  37030. input.attachControl(this.attachedElement, this.noPreventDefault);
  37031. }
  37032. };
  37033. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  37034. if (noPreventDefault === void 0) { noPreventDefault = false; }
  37035. if (this.attachedElement) {
  37036. return;
  37037. }
  37038. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  37039. this.attachedElement = element;
  37040. this.noPreventDefault = noPreventDefault;
  37041. for (var cam in this.attached) {
  37042. this.attached[cam].attachControl(element, noPreventDefault);
  37043. }
  37044. };
  37045. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  37046. if (disconnect === void 0) { disconnect = false; }
  37047. if (this.attachedElement !== element) {
  37048. return;
  37049. }
  37050. for (var cam in this.attached) {
  37051. this.attached[cam].detachControl(element);
  37052. if (disconnect) {
  37053. this.attached[cam].camera = null;
  37054. }
  37055. }
  37056. this.attachedElement = null;
  37057. };
  37058. CameraInputsManager.prototype.rebuildInputCheck = function () {
  37059. this.checkInputs = function () { };
  37060. for (var cam in this.attached) {
  37061. var input = this.attached[cam];
  37062. if (input.checkInputs) {
  37063. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  37064. }
  37065. }
  37066. };
  37067. CameraInputsManager.prototype.clear = function () {
  37068. if (this.attachedElement) {
  37069. this.detachElement(this.attachedElement, true);
  37070. }
  37071. this.attached = {};
  37072. this.attachedElement = null;
  37073. this.checkInputs = function () { };
  37074. };
  37075. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  37076. var inputs = {};
  37077. for (var cam in this.attached) {
  37078. var input = this.attached[cam];
  37079. var res = BABYLON.SerializationHelper.Serialize(input);
  37080. inputs[input.getClassName()] = res;
  37081. }
  37082. serializedCamera.inputsmgr = inputs;
  37083. };
  37084. CameraInputsManager.prototype.parse = function (parsedCamera) {
  37085. var parsedInputs = parsedCamera.inputsmgr;
  37086. if (parsedInputs) {
  37087. this.clear();
  37088. for (var n in parsedInputs) {
  37089. var construct = BABYLON.CameraInputTypes[n];
  37090. if (construct) {
  37091. var parsedinput = parsedInputs[n];
  37092. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  37093. this.add(input);
  37094. }
  37095. }
  37096. }
  37097. else {
  37098. //2016-03-08 this part is for managing backward compatibility
  37099. for (var n in this.attached) {
  37100. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  37101. if (construct) {
  37102. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  37103. this.remove(this.attached[n]);
  37104. this.add(input);
  37105. }
  37106. }
  37107. }
  37108. };
  37109. return CameraInputsManager;
  37110. }());
  37111. BABYLON.CameraInputsManager = CameraInputsManager;
  37112. })(BABYLON || (BABYLON = {}));
  37113. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  37114. var BABYLON;
  37115. (function (BABYLON) {
  37116. var FreeCameraMouseInput = /** @class */ (function () {
  37117. function FreeCameraMouseInput(touchEnabled) {
  37118. if (touchEnabled === void 0) { touchEnabled = true; }
  37119. this.touchEnabled = touchEnabled;
  37120. this.buttons = [0, 1, 2];
  37121. this.angularSensibility = 2000.0;
  37122. this.previousPosition = null;
  37123. }
  37124. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  37125. var _this = this;
  37126. var engine = this.camera.getEngine();
  37127. if (!this._pointerInput) {
  37128. this._pointerInput = function (p, s) {
  37129. var evt = p.event;
  37130. if (engine.isInVRExclusivePointerMode) {
  37131. return;
  37132. }
  37133. if (!_this.touchEnabled && evt.pointerType === "touch") {
  37134. return;
  37135. }
  37136. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  37137. return;
  37138. }
  37139. var srcElement = (evt.srcElement || evt.target);
  37140. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  37141. try {
  37142. srcElement.setPointerCapture(evt.pointerId);
  37143. }
  37144. catch (e) {
  37145. //Nothing to do with the error. Execution will continue.
  37146. }
  37147. _this.previousPosition = {
  37148. x: evt.clientX,
  37149. y: evt.clientY
  37150. };
  37151. if (!noPreventDefault) {
  37152. evt.preventDefault();
  37153. element.focus();
  37154. }
  37155. }
  37156. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  37157. try {
  37158. srcElement.releasePointerCapture(evt.pointerId);
  37159. }
  37160. catch (e) {
  37161. //Nothing to do with the error.
  37162. }
  37163. _this.previousPosition = null;
  37164. if (!noPreventDefault) {
  37165. evt.preventDefault();
  37166. }
  37167. }
  37168. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  37169. if (!_this.previousPosition || engine.isPointerLock) {
  37170. return;
  37171. }
  37172. var offsetX = evt.clientX - _this.previousPosition.x;
  37173. var offsetY = evt.clientY - _this.previousPosition.y;
  37174. if (_this.camera.getScene().useRightHandedSystem) {
  37175. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37176. }
  37177. else {
  37178. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37179. }
  37180. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37181. _this.previousPosition = {
  37182. x: evt.clientX,
  37183. y: evt.clientY
  37184. };
  37185. if (!noPreventDefault) {
  37186. evt.preventDefault();
  37187. }
  37188. }
  37189. };
  37190. }
  37191. this._onMouseMove = function (evt) {
  37192. if (!engine.isPointerLock) {
  37193. return;
  37194. }
  37195. if (engine.isInVRExclusivePointerMode) {
  37196. return;
  37197. }
  37198. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  37199. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  37200. if (_this.camera.getScene().useRightHandedSystem) {
  37201. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  37202. }
  37203. else {
  37204. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  37205. }
  37206. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  37207. _this.previousPosition = null;
  37208. if (!noPreventDefault) {
  37209. evt.preventDefault();
  37210. }
  37211. };
  37212. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  37213. element.addEventListener("mousemove", this._onMouseMove, false);
  37214. };
  37215. FreeCameraMouseInput.prototype.detachControl = function (element) {
  37216. if (this._observer && element) {
  37217. this.camera.getScene().onPointerObservable.remove(this._observer);
  37218. if (this._onMouseMove) {
  37219. element.removeEventListener("mousemove", this._onMouseMove);
  37220. }
  37221. this._observer = null;
  37222. this._onMouseMove = null;
  37223. this.previousPosition = null;
  37224. }
  37225. };
  37226. FreeCameraMouseInput.prototype.getClassName = function () {
  37227. return "FreeCameraMouseInput";
  37228. };
  37229. FreeCameraMouseInput.prototype.getSimpleName = function () {
  37230. return "mouse";
  37231. };
  37232. __decorate([
  37233. BABYLON.serialize()
  37234. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  37235. __decorate([
  37236. BABYLON.serialize()
  37237. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  37238. return FreeCameraMouseInput;
  37239. }());
  37240. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  37241. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  37242. })(BABYLON || (BABYLON = {}));
  37243. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  37244. var BABYLON;
  37245. (function (BABYLON) {
  37246. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  37247. function FreeCameraKeyboardMoveInput() {
  37248. this._keys = new Array();
  37249. this.keysUp = [38];
  37250. this.keysDown = [40];
  37251. this.keysLeft = [37];
  37252. this.keysRight = [39];
  37253. }
  37254. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37255. var _this = this;
  37256. if (this._onCanvasBlurObserver) {
  37257. return;
  37258. }
  37259. this._scene = this.camera.getScene();
  37260. this._engine = this._scene.getEngine();
  37261. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37262. _this._keys = [];
  37263. });
  37264. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37265. var evt = info.event;
  37266. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37267. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37268. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37269. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37270. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37271. var index = _this._keys.indexOf(evt.keyCode);
  37272. if (index === -1) {
  37273. _this._keys.push(evt.keyCode);
  37274. }
  37275. if (!noPreventDefault) {
  37276. evt.preventDefault();
  37277. }
  37278. }
  37279. }
  37280. else {
  37281. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37282. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37283. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37284. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  37285. var index = _this._keys.indexOf(evt.keyCode);
  37286. if (index >= 0) {
  37287. _this._keys.splice(index, 1);
  37288. }
  37289. if (!noPreventDefault) {
  37290. evt.preventDefault();
  37291. }
  37292. }
  37293. }
  37294. });
  37295. };
  37296. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37297. if (this._scene) {
  37298. if (this._onKeyboardObserver) {
  37299. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37300. }
  37301. if (this._onCanvasBlurObserver) {
  37302. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37303. }
  37304. this._onKeyboardObserver = null;
  37305. this._onCanvasBlurObserver = null;
  37306. }
  37307. this._keys = [];
  37308. };
  37309. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37310. if (this._onKeyboardObserver) {
  37311. var camera = this.camera;
  37312. // Keyboard
  37313. for (var index = 0; index < this._keys.length; index++) {
  37314. var keyCode = this._keys[index];
  37315. var speed = camera._computeLocalCameraSpeed();
  37316. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37317. camera._localDirection.copyFromFloats(-speed, 0, 0);
  37318. }
  37319. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37320. camera._localDirection.copyFromFloats(0, 0, speed);
  37321. }
  37322. else if (this.keysRight.indexOf(keyCode) !== -1) {
  37323. camera._localDirection.copyFromFloats(speed, 0, 0);
  37324. }
  37325. else if (this.keysDown.indexOf(keyCode) !== -1) {
  37326. camera._localDirection.copyFromFloats(0, 0, -speed);
  37327. }
  37328. if (camera.getScene().useRightHandedSystem) {
  37329. camera._localDirection.z *= -1;
  37330. }
  37331. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  37332. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  37333. camera.cameraDirection.addInPlace(camera._transformedDirection);
  37334. }
  37335. }
  37336. };
  37337. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  37338. return "FreeCameraKeyboardMoveInput";
  37339. };
  37340. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  37341. this._keys = [];
  37342. };
  37343. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  37344. return "keyboard";
  37345. };
  37346. __decorate([
  37347. BABYLON.serialize()
  37348. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  37349. __decorate([
  37350. BABYLON.serialize()
  37351. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  37352. __decorate([
  37353. BABYLON.serialize()
  37354. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  37355. __decorate([
  37356. BABYLON.serialize()
  37357. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  37358. return FreeCameraKeyboardMoveInput;
  37359. }());
  37360. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  37361. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  37362. })(BABYLON || (BABYLON = {}));
  37363. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  37364. var BABYLON;
  37365. (function (BABYLON) {
  37366. var FreeCameraInputsManager = /** @class */ (function (_super) {
  37367. __extends(FreeCameraInputsManager, _super);
  37368. function FreeCameraInputsManager(camera) {
  37369. return _super.call(this, camera) || this;
  37370. }
  37371. FreeCameraInputsManager.prototype.addKeyboard = function () {
  37372. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  37373. return this;
  37374. };
  37375. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  37376. if (touchEnabled === void 0) { touchEnabled = true; }
  37377. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  37378. return this;
  37379. };
  37380. FreeCameraInputsManager.prototype.addGamepad = function () {
  37381. this.add(new BABYLON.FreeCameraGamepadInput());
  37382. return this;
  37383. };
  37384. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  37385. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  37386. return this;
  37387. };
  37388. FreeCameraInputsManager.prototype.addTouch = function () {
  37389. this.add(new BABYLON.FreeCameraTouchInput());
  37390. return this;
  37391. };
  37392. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  37393. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  37394. return this;
  37395. };
  37396. return FreeCameraInputsManager;
  37397. }(BABYLON.CameraInputsManager));
  37398. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  37399. })(BABYLON || (BABYLON = {}));
  37400. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  37401. var BABYLON;
  37402. (function (BABYLON) {
  37403. var TargetCamera = /** @class */ (function (_super) {
  37404. __extends(TargetCamera, _super);
  37405. function TargetCamera(name, position, scene) {
  37406. var _this = _super.call(this, name, position, scene) || this;
  37407. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37408. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  37409. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  37410. _this.speed = 2.0;
  37411. _this.noRotationConstraint = false;
  37412. _this.lockedTarget = null;
  37413. _this._currentTarget = BABYLON.Vector3.Zero();
  37414. _this._viewMatrix = BABYLON.Matrix.Zero();
  37415. _this._camMatrix = BABYLON.Matrix.Zero();
  37416. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  37417. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  37418. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  37419. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  37420. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  37421. _this._lookAtTemp = BABYLON.Matrix.Zero();
  37422. _this._tempMatrix = BABYLON.Matrix.Zero();
  37423. return _this;
  37424. }
  37425. TargetCamera.prototype.getFrontPosition = function (distance) {
  37426. var direction = this.getTarget().subtract(this.position);
  37427. direction.normalize();
  37428. direction.scaleInPlace(distance);
  37429. return this.globalPosition.add(direction);
  37430. };
  37431. TargetCamera.prototype._getLockedTargetPosition = function () {
  37432. if (!this.lockedTarget) {
  37433. return null;
  37434. }
  37435. if (this.lockedTarget.absolutePosition) {
  37436. this.lockedTarget.computeWorldMatrix();
  37437. }
  37438. return this.lockedTarget.absolutePosition || this.lockedTarget;
  37439. };
  37440. TargetCamera.prototype.storeState = function () {
  37441. this._storedPosition = this.position.clone();
  37442. this._storedRotation = this.rotation.clone();
  37443. if (this.rotationQuaternion) {
  37444. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  37445. }
  37446. return _super.prototype.storeState.call(this);
  37447. };
  37448. /**
  37449. * Restored camera state. You must call storeState() first
  37450. */
  37451. TargetCamera.prototype._restoreStateValues = function () {
  37452. if (!_super.prototype._restoreStateValues.call(this)) {
  37453. return false;
  37454. }
  37455. this.position = this._storedPosition.clone();
  37456. this.rotation = this._storedRotation.clone();
  37457. if (this.rotationQuaternion) {
  37458. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  37459. }
  37460. this.cameraDirection.copyFromFloats(0, 0, 0);
  37461. this.cameraRotation.copyFromFloats(0, 0);
  37462. return true;
  37463. };
  37464. // Cache
  37465. TargetCamera.prototype._initCache = function () {
  37466. _super.prototype._initCache.call(this);
  37467. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37468. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37469. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  37470. };
  37471. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  37472. if (!ignoreParentClass) {
  37473. _super.prototype._updateCache.call(this);
  37474. }
  37475. var lockedTargetPosition = this._getLockedTargetPosition();
  37476. if (!lockedTargetPosition) {
  37477. this._cache.lockedTarget = null;
  37478. }
  37479. else {
  37480. if (!this._cache.lockedTarget) {
  37481. this._cache.lockedTarget = lockedTargetPosition.clone();
  37482. }
  37483. else {
  37484. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  37485. }
  37486. }
  37487. this._cache.rotation.copyFrom(this.rotation);
  37488. if (this.rotationQuaternion)
  37489. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37490. };
  37491. // Synchronized
  37492. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  37493. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  37494. return false;
  37495. }
  37496. var lockedTargetPosition = this._getLockedTargetPosition();
  37497. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  37498. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  37499. };
  37500. // Methods
  37501. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  37502. var engine = this.getEngine();
  37503. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  37504. };
  37505. // Target
  37506. TargetCamera.prototype.setTarget = function (target) {
  37507. this.upVector.normalize();
  37508. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  37509. this._camMatrix.invert();
  37510. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  37511. var vDir = target.subtract(this.position);
  37512. if (vDir.x >= 0.0) {
  37513. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  37514. }
  37515. else {
  37516. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  37517. }
  37518. this.rotation.z = 0;
  37519. if (isNaN(this.rotation.x)) {
  37520. this.rotation.x = 0;
  37521. }
  37522. if (isNaN(this.rotation.y)) {
  37523. this.rotation.y = 0;
  37524. }
  37525. if (isNaN(this.rotation.z)) {
  37526. this.rotation.z = 0;
  37527. }
  37528. if (this.rotationQuaternion) {
  37529. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37530. }
  37531. };
  37532. /**
  37533. * Return the current target position of the camera. This value is expressed in local space.
  37534. */
  37535. TargetCamera.prototype.getTarget = function () {
  37536. return this._currentTarget;
  37537. };
  37538. TargetCamera.prototype._decideIfNeedsToMove = function () {
  37539. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37540. };
  37541. TargetCamera.prototype._updatePosition = function () {
  37542. if (this.parent) {
  37543. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  37544. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  37545. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  37546. return;
  37547. }
  37548. this.position.addInPlace(this.cameraDirection);
  37549. };
  37550. TargetCamera.prototype._checkInputs = function () {
  37551. var needToMove = this._decideIfNeedsToMove();
  37552. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  37553. // Move
  37554. if (needToMove) {
  37555. this._updatePosition();
  37556. }
  37557. // Rotate
  37558. if (needToRotate) {
  37559. this.rotation.x += this.cameraRotation.x;
  37560. this.rotation.y += this.cameraRotation.y;
  37561. //rotate, if quaternion is set and rotation was used
  37562. if (this.rotationQuaternion) {
  37563. var len = this.rotation.lengthSquared();
  37564. if (len) {
  37565. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  37566. }
  37567. }
  37568. if (!this.noRotationConstraint) {
  37569. var limit = (Math.PI / 2) * 0.95;
  37570. if (this.rotation.x > limit)
  37571. this.rotation.x = limit;
  37572. if (this.rotation.x < -limit)
  37573. this.rotation.x = -limit;
  37574. }
  37575. }
  37576. // Inertia
  37577. if (needToMove) {
  37578. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  37579. this.cameraDirection.x = 0;
  37580. }
  37581. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  37582. this.cameraDirection.y = 0;
  37583. }
  37584. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  37585. this.cameraDirection.z = 0;
  37586. }
  37587. this.cameraDirection.scaleInPlace(this.inertia);
  37588. }
  37589. if (needToRotate) {
  37590. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  37591. this.cameraRotation.x = 0;
  37592. }
  37593. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  37594. this.cameraRotation.y = 0;
  37595. }
  37596. this.cameraRotation.scaleInPlace(this.inertia);
  37597. }
  37598. _super.prototype._checkInputs.call(this);
  37599. };
  37600. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  37601. if (this.rotationQuaternion) {
  37602. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  37603. }
  37604. else {
  37605. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  37606. }
  37607. //update the up vector!
  37608. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  37609. };
  37610. TargetCamera.prototype._getViewMatrix = function () {
  37611. if (!this.lockedTarget) {
  37612. // Compute
  37613. this._updateCameraRotationMatrix();
  37614. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  37615. // Computing target and final matrix
  37616. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  37617. }
  37618. else {
  37619. var targetPosition = this._getLockedTargetPosition();
  37620. if (targetPosition) {
  37621. this._currentTarget.copyFrom(targetPosition);
  37622. }
  37623. }
  37624. if (this.getScene().useRightHandedSystem) {
  37625. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37626. }
  37627. else {
  37628. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  37629. }
  37630. return this._viewMatrix;
  37631. };
  37632. /**
  37633. * @override
  37634. * Override Camera.createRigCamera
  37635. */
  37636. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  37637. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  37638. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  37639. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  37640. if (!this.rotationQuaternion) {
  37641. this.rotationQuaternion = new BABYLON.Quaternion();
  37642. }
  37643. rigCamera._cameraRigParams = {};
  37644. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  37645. }
  37646. return rigCamera;
  37647. }
  37648. return null;
  37649. };
  37650. /**
  37651. * @override
  37652. * Override Camera._updateRigCameras
  37653. */
  37654. TargetCamera.prototype._updateRigCameras = function () {
  37655. var camLeft = this._rigCameras[0];
  37656. var camRight = this._rigCameras[1];
  37657. switch (this.cameraRigMode) {
  37658. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  37659. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  37660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  37661. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  37662. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  37663. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  37664. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  37665. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  37666. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  37667. camLeft.setTarget(this.getTarget());
  37668. camRight.setTarget(this.getTarget());
  37669. break;
  37670. case BABYLON.Camera.RIG_MODE_VR:
  37671. if (camLeft.rotationQuaternion) {
  37672. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37673. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  37674. }
  37675. else {
  37676. camLeft.rotation.copyFrom(this.rotation);
  37677. camRight.rotation.copyFrom(this.rotation);
  37678. }
  37679. camLeft.position.copyFrom(this.position);
  37680. camRight.position.copyFrom(this.position);
  37681. break;
  37682. }
  37683. _super.prototype._updateRigCameras.call(this);
  37684. };
  37685. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  37686. if (!this._rigCamTransformMatrix) {
  37687. this._rigCamTransformMatrix = new BABYLON.Matrix();
  37688. }
  37689. var target = this.getTarget();
  37690. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  37691. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  37692. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  37693. };
  37694. TargetCamera.prototype.getClassName = function () {
  37695. return "TargetCamera";
  37696. };
  37697. __decorate([
  37698. BABYLON.serializeAsVector3()
  37699. ], TargetCamera.prototype, "rotation", void 0);
  37700. __decorate([
  37701. BABYLON.serialize()
  37702. ], TargetCamera.prototype, "speed", void 0);
  37703. __decorate([
  37704. BABYLON.serializeAsMeshReference("lockedTargetId")
  37705. ], TargetCamera.prototype, "lockedTarget", void 0);
  37706. return TargetCamera;
  37707. }(BABYLON.Camera));
  37708. BABYLON.TargetCamera = TargetCamera;
  37709. })(BABYLON || (BABYLON = {}));
  37710. //# sourceMappingURL=babylon.targetCamera.js.map
  37711. var BABYLON;
  37712. (function (BABYLON) {
  37713. var FreeCamera = /** @class */ (function (_super) {
  37714. __extends(FreeCamera, _super);
  37715. function FreeCamera(name, position, scene) {
  37716. var _this = _super.call(this, name, position, scene) || this;
  37717. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  37718. _this.checkCollisions = false;
  37719. _this.applyGravity = false;
  37720. _this._needMoveForGravity = false;
  37721. _this._oldPosition = BABYLON.Vector3.Zero();
  37722. _this._diffPosition = BABYLON.Vector3.Zero();
  37723. _this._newPosition = BABYLON.Vector3.Zero();
  37724. // Collisions
  37725. _this._collisionMask = -1;
  37726. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  37727. if (collidedMesh === void 0) { collidedMesh = null; }
  37728. //TODO move this to the collision coordinator!
  37729. if (_this.getScene().workerCollisions)
  37730. newPosition.multiplyInPlace(_this._collider.radius);
  37731. var updatePosition = function (newPos) {
  37732. _this._newPosition.copyFrom(newPos);
  37733. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  37734. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  37735. _this.position.addInPlace(_this._diffPosition);
  37736. if (_this.onCollide && collidedMesh) {
  37737. _this.onCollide(collidedMesh);
  37738. }
  37739. }
  37740. };
  37741. updatePosition(newPosition);
  37742. };
  37743. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  37744. _this.inputs.addKeyboard().addMouse();
  37745. return _this;
  37746. }
  37747. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  37748. //-- begin properties for backward compatibility for inputs
  37749. get: function () {
  37750. var mouse = this.inputs.attached["mouse"];
  37751. if (mouse)
  37752. return mouse.angularSensibility;
  37753. return 0;
  37754. },
  37755. set: function (value) {
  37756. var mouse = this.inputs.attached["mouse"];
  37757. if (mouse)
  37758. mouse.angularSensibility = value;
  37759. },
  37760. enumerable: true,
  37761. configurable: true
  37762. });
  37763. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  37764. get: function () {
  37765. var keyboard = this.inputs.attached["keyboard"];
  37766. if (keyboard)
  37767. return keyboard.keysUp;
  37768. return [];
  37769. },
  37770. set: function (value) {
  37771. var keyboard = this.inputs.attached["keyboard"];
  37772. if (keyboard)
  37773. keyboard.keysUp = value;
  37774. },
  37775. enumerable: true,
  37776. configurable: true
  37777. });
  37778. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  37779. get: function () {
  37780. var keyboard = this.inputs.attached["keyboard"];
  37781. if (keyboard)
  37782. return keyboard.keysDown;
  37783. return [];
  37784. },
  37785. set: function (value) {
  37786. var keyboard = this.inputs.attached["keyboard"];
  37787. if (keyboard)
  37788. keyboard.keysDown = value;
  37789. },
  37790. enumerable: true,
  37791. configurable: true
  37792. });
  37793. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  37794. get: function () {
  37795. var keyboard = this.inputs.attached["keyboard"];
  37796. if (keyboard)
  37797. return keyboard.keysLeft;
  37798. return [];
  37799. },
  37800. set: function (value) {
  37801. var keyboard = this.inputs.attached["keyboard"];
  37802. if (keyboard)
  37803. keyboard.keysLeft = value;
  37804. },
  37805. enumerable: true,
  37806. configurable: true
  37807. });
  37808. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  37809. get: function () {
  37810. var keyboard = this.inputs.attached["keyboard"];
  37811. if (keyboard)
  37812. return keyboard.keysRight;
  37813. return [];
  37814. },
  37815. set: function (value) {
  37816. var keyboard = this.inputs.attached["keyboard"];
  37817. if (keyboard)
  37818. keyboard.keysRight = value;
  37819. },
  37820. enumerable: true,
  37821. configurable: true
  37822. });
  37823. // Controls
  37824. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  37825. this.inputs.attachElement(element, noPreventDefault);
  37826. };
  37827. FreeCamera.prototype.detachControl = function (element) {
  37828. this.inputs.detachElement(element);
  37829. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  37830. this.cameraRotation = new BABYLON.Vector2(0, 0);
  37831. };
  37832. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  37833. get: function () {
  37834. return this._collisionMask;
  37835. },
  37836. set: function (mask) {
  37837. this._collisionMask = !isNaN(mask) ? mask : -1;
  37838. },
  37839. enumerable: true,
  37840. configurable: true
  37841. });
  37842. FreeCamera.prototype._collideWithWorld = function (displacement) {
  37843. var globalPosition;
  37844. if (this.parent) {
  37845. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  37846. }
  37847. else {
  37848. globalPosition = this.position;
  37849. }
  37850. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  37851. if (!this._collider) {
  37852. this._collider = new BABYLON.Collider();
  37853. }
  37854. this._collider.radius = this.ellipsoid;
  37855. this._collider.collisionMask = this._collisionMask;
  37856. //no need for clone, as long as gravity is not on.
  37857. var actualDisplacement = displacement;
  37858. //add gravity to the direction to prevent the dual-collision checking
  37859. if (this.applyGravity) {
  37860. //this prevents mending with cameraDirection, a global variable of the free camera class.
  37861. actualDisplacement = displacement.add(this.getScene().gravity);
  37862. }
  37863. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  37864. };
  37865. FreeCamera.prototype._checkInputs = function () {
  37866. if (!this._localDirection) {
  37867. this._localDirection = BABYLON.Vector3.Zero();
  37868. this._transformedDirection = BABYLON.Vector3.Zero();
  37869. }
  37870. this.inputs.checkInputs();
  37871. _super.prototype._checkInputs.call(this);
  37872. };
  37873. FreeCamera.prototype._decideIfNeedsToMove = function () {
  37874. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  37875. };
  37876. FreeCamera.prototype._updatePosition = function () {
  37877. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  37878. this._collideWithWorld(this.cameraDirection);
  37879. }
  37880. else {
  37881. _super.prototype._updatePosition.call(this);
  37882. }
  37883. };
  37884. FreeCamera.prototype.dispose = function () {
  37885. this.inputs.clear();
  37886. _super.prototype.dispose.call(this);
  37887. };
  37888. FreeCamera.prototype.getClassName = function () {
  37889. return "FreeCamera";
  37890. };
  37891. __decorate([
  37892. BABYLON.serializeAsVector3()
  37893. ], FreeCamera.prototype, "ellipsoid", void 0);
  37894. __decorate([
  37895. BABYLON.serialize()
  37896. ], FreeCamera.prototype, "checkCollisions", void 0);
  37897. __decorate([
  37898. BABYLON.serialize()
  37899. ], FreeCamera.prototype, "applyGravity", void 0);
  37900. return FreeCamera;
  37901. }(BABYLON.TargetCamera));
  37902. BABYLON.FreeCamera = FreeCamera;
  37903. })(BABYLON || (BABYLON = {}));
  37904. //# sourceMappingURL=babylon.freeCamera.js.map
  37905. var BABYLON;
  37906. (function (BABYLON) {
  37907. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  37908. function ArcRotateCameraKeyboardMoveInput() {
  37909. this._keys = new Array();
  37910. this.keysUp = [38];
  37911. this.keysDown = [40];
  37912. this.keysLeft = [37];
  37913. this.keysRight = [39];
  37914. this.keysReset = [220];
  37915. this.panningSensibility = 50.0;
  37916. this.zoomingSensibility = 25.0;
  37917. this.useAltToZoom = true;
  37918. }
  37919. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  37920. var _this = this;
  37921. if (this._onCanvasBlurObserver) {
  37922. return;
  37923. }
  37924. this._scene = this.camera.getScene();
  37925. this._engine = this._scene.getEngine();
  37926. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  37927. _this._keys = [];
  37928. });
  37929. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  37930. var evt = info.event;
  37931. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  37932. _this._ctrlPressed = evt.ctrlKey;
  37933. _this._altPressed = evt.altKey;
  37934. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37935. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37936. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37937. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37938. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37939. var index = _this._keys.indexOf(evt.keyCode);
  37940. if (index === -1) {
  37941. _this._keys.push(evt.keyCode);
  37942. }
  37943. if (evt.preventDefault) {
  37944. if (!noPreventDefault) {
  37945. evt.preventDefault();
  37946. }
  37947. }
  37948. }
  37949. }
  37950. else {
  37951. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  37952. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  37953. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  37954. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  37955. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  37956. var index = _this._keys.indexOf(evt.keyCode);
  37957. if (index >= 0) {
  37958. _this._keys.splice(index, 1);
  37959. }
  37960. if (evt.preventDefault) {
  37961. if (!noPreventDefault) {
  37962. evt.preventDefault();
  37963. }
  37964. }
  37965. }
  37966. }
  37967. });
  37968. };
  37969. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  37970. if (this._scene) {
  37971. if (this._onKeyboardObserver) {
  37972. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  37973. }
  37974. if (this._onCanvasBlurObserver) {
  37975. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  37976. }
  37977. this._onKeyboardObserver = null;
  37978. this._onCanvasBlurObserver = null;
  37979. }
  37980. this._keys = [];
  37981. };
  37982. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  37983. if (this._onKeyboardObserver) {
  37984. var camera = this.camera;
  37985. for (var index = 0; index < this._keys.length; index++) {
  37986. var keyCode = this._keys[index];
  37987. if (this.keysLeft.indexOf(keyCode) !== -1) {
  37988. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37989. camera.inertialPanningX -= 1 / this.panningSensibility;
  37990. }
  37991. else {
  37992. camera.inertialAlphaOffset -= 0.01;
  37993. }
  37994. }
  37995. else if (this.keysUp.indexOf(keyCode) !== -1) {
  37996. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  37997. camera.inertialPanningY += 1 / this.panningSensibility;
  37998. }
  37999. else if (this._altPressed && this.useAltToZoom) {
  38000. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  38001. }
  38002. else {
  38003. camera.inertialBetaOffset -= 0.01;
  38004. }
  38005. }
  38006. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38007. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38008. camera.inertialPanningX += 1 / this.panningSensibility;
  38009. }
  38010. else {
  38011. camera.inertialAlphaOffset += 0.01;
  38012. }
  38013. }
  38014. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38015. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  38016. camera.inertialPanningY -= 1 / this.panningSensibility;
  38017. }
  38018. else if (this._altPressed && this.useAltToZoom) {
  38019. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  38020. }
  38021. else {
  38022. camera.inertialBetaOffset += 0.01;
  38023. }
  38024. }
  38025. else if (this.keysReset.indexOf(keyCode) !== -1) {
  38026. camera.restoreState();
  38027. }
  38028. }
  38029. }
  38030. };
  38031. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  38032. return "ArcRotateCameraKeyboardMoveInput";
  38033. };
  38034. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38035. return "keyboard";
  38036. };
  38037. __decorate([
  38038. BABYLON.serialize()
  38039. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38040. __decorate([
  38041. BABYLON.serialize()
  38042. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38043. __decorate([
  38044. BABYLON.serialize()
  38045. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38046. __decorate([
  38047. BABYLON.serialize()
  38048. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38049. __decorate([
  38050. BABYLON.serialize()
  38051. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  38052. __decorate([
  38053. BABYLON.serialize()
  38054. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  38055. __decorate([
  38056. BABYLON.serialize()
  38057. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  38058. __decorate([
  38059. BABYLON.serialize()
  38060. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  38061. return ArcRotateCameraKeyboardMoveInput;
  38062. }());
  38063. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  38064. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  38065. })(BABYLON || (BABYLON = {}));
  38066. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  38067. var BABYLON;
  38068. (function (BABYLON) {
  38069. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  38070. function ArcRotateCameraMouseWheelInput() {
  38071. this.wheelPrecision = 3.0;
  38072. /**
  38073. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  38074. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  38075. */
  38076. this.wheelDeltaPercentage = 0;
  38077. }
  38078. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  38079. var _this = this;
  38080. this._wheel = function (p, s) {
  38081. //sanity check - this should be a PointerWheel event.
  38082. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  38083. return;
  38084. var event = p.event;
  38085. var delta = 0;
  38086. if (event.wheelDelta) {
  38087. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  38088. }
  38089. else if (event.detail) {
  38090. delta = -event.detail / _this.wheelPrecision;
  38091. }
  38092. if (delta)
  38093. _this.camera.inertialRadiusOffset += delta;
  38094. if (event.preventDefault) {
  38095. if (!noPreventDefault) {
  38096. event.preventDefault();
  38097. }
  38098. }
  38099. };
  38100. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  38101. };
  38102. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  38103. if (this._observer && element) {
  38104. this.camera.getScene().onPointerObservable.remove(this._observer);
  38105. this._observer = null;
  38106. this._wheel = null;
  38107. }
  38108. };
  38109. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  38110. return "ArcRotateCameraMouseWheelInput";
  38111. };
  38112. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  38113. return "mousewheel";
  38114. };
  38115. __decorate([
  38116. BABYLON.serialize()
  38117. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  38118. __decorate([
  38119. BABYLON.serialize()
  38120. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  38121. return ArcRotateCameraMouseWheelInput;
  38122. }());
  38123. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  38124. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  38125. })(BABYLON || (BABYLON = {}));
  38126. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  38127. var BABYLON;
  38128. (function (BABYLON) {
  38129. var ArcRotateCameraPointersInput = /** @class */ (function () {
  38130. function ArcRotateCameraPointersInput() {
  38131. this.buttons = [0, 1, 2];
  38132. this.angularSensibilityX = 1000.0;
  38133. this.angularSensibilityY = 1000.0;
  38134. this.pinchPrecision = 12.0;
  38135. /**
  38136. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  38137. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  38138. */
  38139. this.pinchDeltaPercentage = 0;
  38140. this.panningSensibility = 1000.0;
  38141. this.multiTouchPanning = true;
  38142. this.multiTouchPanAndZoom = true;
  38143. this._isPanClick = false;
  38144. this.pinchInwards = true;
  38145. }
  38146. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  38147. var _this = this;
  38148. var engine = this.camera.getEngine();
  38149. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  38150. var pointA = null;
  38151. var pointB = null;
  38152. var previousPinchSquaredDistance = 0;
  38153. var initialDistance = 0;
  38154. var twoFingerActivityCount = 0;
  38155. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  38156. this._pointerInput = function (p, s) {
  38157. var evt = p.event;
  38158. var isTouch = p.event.pointerType === "touch";
  38159. if (engine.isInVRExclusivePointerMode) {
  38160. return;
  38161. }
  38162. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38163. return;
  38164. }
  38165. var srcElement = (evt.srcElement || evt.target);
  38166. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38167. try {
  38168. srcElement.setPointerCapture(evt.pointerId);
  38169. }
  38170. catch (e) {
  38171. //Nothing to do with the error. Execution will continue.
  38172. }
  38173. // Manage panning with pan button click
  38174. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  38175. // manage pointers
  38176. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  38177. if (pointA === null) {
  38178. pointA = cacheSoloPointer;
  38179. }
  38180. else if (pointB === null) {
  38181. pointB = cacheSoloPointer;
  38182. }
  38183. if (!noPreventDefault) {
  38184. evt.preventDefault();
  38185. element.focus();
  38186. }
  38187. }
  38188. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  38189. _this.camera.restoreState();
  38190. }
  38191. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38192. try {
  38193. srcElement.releasePointerCapture(evt.pointerId);
  38194. }
  38195. catch (e) {
  38196. //Nothing to do with the error.
  38197. }
  38198. cacheSoloPointer = null;
  38199. previousPinchSquaredDistance = 0;
  38200. previousMultiTouchPanPosition.isPaning = false;
  38201. previousMultiTouchPanPosition.isPinching = false;
  38202. twoFingerActivityCount = 0;
  38203. initialDistance = 0;
  38204. if (!isTouch) {
  38205. pointB = null; // Mouse and pen are mono pointer
  38206. }
  38207. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  38208. //but emptying completly pointers collection is required to fix a bug on iPhone :
  38209. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  38210. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  38211. if (engine.badOS) {
  38212. pointA = pointB = null;
  38213. }
  38214. else {
  38215. //only remove the impacted pointer in case of multitouch allowing on most
  38216. //platforms switching from rotate to zoom and pan seamlessly.
  38217. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  38218. pointA = pointB;
  38219. pointB = null;
  38220. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38221. }
  38222. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  38223. pointB = null;
  38224. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  38225. }
  38226. else {
  38227. pointA = pointB = null;
  38228. }
  38229. }
  38230. if (!noPreventDefault) {
  38231. evt.preventDefault();
  38232. }
  38233. }
  38234. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38235. if (!noPreventDefault) {
  38236. evt.preventDefault();
  38237. }
  38238. // One button down
  38239. if (pointA && pointB === null && cacheSoloPointer) {
  38240. if (_this.panningSensibility !== 0 &&
  38241. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  38242. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  38243. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  38244. }
  38245. else {
  38246. var offsetX = evt.clientX - cacheSoloPointer.x;
  38247. var offsetY = evt.clientY - cacheSoloPointer.y;
  38248. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38249. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38250. }
  38251. cacheSoloPointer.x = evt.clientX;
  38252. cacheSoloPointer.y = evt.clientY;
  38253. }
  38254. else if (pointA && pointB) {
  38255. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  38256. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  38257. ed.x = evt.clientX;
  38258. ed.y = evt.clientY;
  38259. var direction = _this.pinchInwards ? 1 : -1;
  38260. var distX = pointA.x - pointB.x;
  38261. var distY = pointA.y - pointB.y;
  38262. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  38263. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  38264. if (previousPinchSquaredDistance === 0) {
  38265. initialDistance = pinchDistance;
  38266. previousPinchSquaredDistance = pinchSquaredDistance;
  38267. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  38268. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  38269. return;
  38270. }
  38271. if (_this.multiTouchPanAndZoom) {
  38272. if (_this.pinchDeltaPercentage) {
  38273. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38274. }
  38275. else {
  38276. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38277. (_this.pinchPrecision *
  38278. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38279. direction);
  38280. }
  38281. if (_this.panningSensibility !== 0) {
  38282. var pointersCenterX = (pointA.x + pointB.x) / 2;
  38283. var pointersCenterY = (pointA.y + pointB.y) / 2;
  38284. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  38285. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  38286. previousMultiTouchPanPosition.x = pointersCenterX;
  38287. previousMultiTouchPanPosition.y = pointersCenterY;
  38288. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  38289. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  38290. }
  38291. }
  38292. else {
  38293. twoFingerActivityCount++;
  38294. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  38295. if (_this.pinchDeltaPercentage) {
  38296. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  38297. }
  38298. else {
  38299. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  38300. (_this.pinchPrecision *
  38301. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  38302. direction);
  38303. }
  38304. previousMultiTouchPanPosition.isPaning = false;
  38305. previousMultiTouchPanPosition.isPinching = true;
  38306. }
  38307. else {
  38308. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  38309. if (!previousMultiTouchPanPosition.isPaning) {
  38310. previousMultiTouchPanPosition.isPaning = true;
  38311. previousMultiTouchPanPosition.isPinching = false;
  38312. previousMultiTouchPanPosition.x = ed.x;
  38313. previousMultiTouchPanPosition.y = ed.y;
  38314. return;
  38315. }
  38316. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  38317. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  38318. }
  38319. }
  38320. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  38321. previousMultiTouchPanPosition.x = ed.x;
  38322. previousMultiTouchPanPosition.y = ed.y;
  38323. }
  38324. }
  38325. previousPinchSquaredDistance = pinchSquaredDistance;
  38326. }
  38327. }
  38328. };
  38329. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  38330. this._onContextMenu = function (evt) {
  38331. evt.preventDefault();
  38332. };
  38333. if (!this.camera._useCtrlForPanning) {
  38334. element.addEventListener("contextmenu", this._onContextMenu, false);
  38335. }
  38336. this._onLostFocus = function () {
  38337. //this._keys = [];
  38338. pointA = pointB = null;
  38339. previousPinchSquaredDistance = 0;
  38340. previousMultiTouchPanPosition.isPaning = false;
  38341. previousMultiTouchPanPosition.isPinching = false;
  38342. twoFingerActivityCount = 0;
  38343. cacheSoloPointer = null;
  38344. initialDistance = 0;
  38345. };
  38346. this._onMouseMove = function (evt) {
  38347. if (!engine.isPointerLock) {
  38348. return;
  38349. }
  38350. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38351. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38352. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  38353. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  38354. if (!noPreventDefault) {
  38355. evt.preventDefault();
  38356. }
  38357. };
  38358. this._onGestureStart = function (e) {
  38359. if (window.MSGesture === undefined) {
  38360. return;
  38361. }
  38362. if (!_this._MSGestureHandler) {
  38363. _this._MSGestureHandler = new MSGesture();
  38364. _this._MSGestureHandler.target = element;
  38365. }
  38366. _this._MSGestureHandler.addPointer(e.pointerId);
  38367. };
  38368. this._onGesture = function (e) {
  38369. _this.camera.radius *= e.scale;
  38370. if (e.preventDefault) {
  38371. if (!noPreventDefault) {
  38372. e.stopPropagation();
  38373. e.preventDefault();
  38374. }
  38375. }
  38376. };
  38377. element.addEventListener("mousemove", this._onMouseMove, false);
  38378. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  38379. element.addEventListener("MSGestureChange", this._onGesture, false);
  38380. BABYLON.Tools.RegisterTopRootEvents([
  38381. { name: "blur", handler: this._onLostFocus }
  38382. ]);
  38383. };
  38384. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  38385. if (this._onLostFocus) {
  38386. BABYLON.Tools.UnregisterTopRootEvents([
  38387. { name: "blur", handler: this._onLostFocus }
  38388. ]);
  38389. }
  38390. if (element && this._observer) {
  38391. this.camera.getScene().onPointerObservable.remove(this._observer);
  38392. this._observer = null;
  38393. if (this._onContextMenu) {
  38394. element.removeEventListener("contextmenu", this._onContextMenu);
  38395. }
  38396. if (this._onMouseMove) {
  38397. element.removeEventListener("mousemove", this._onMouseMove);
  38398. }
  38399. if (this._onGestureStart) {
  38400. element.removeEventListener("MSPointerDown", this._onGestureStart);
  38401. }
  38402. if (this._onGesture) {
  38403. element.removeEventListener("MSGestureChange", this._onGesture);
  38404. }
  38405. this._isPanClick = false;
  38406. this.pinchInwards = true;
  38407. this._onMouseMove = null;
  38408. this._onGestureStart = null;
  38409. this._onGesture = null;
  38410. this._MSGestureHandler = null;
  38411. this._onLostFocus = null;
  38412. this._onContextMenu = null;
  38413. }
  38414. };
  38415. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  38416. return "ArcRotateCameraPointersInput";
  38417. };
  38418. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  38419. return "pointers";
  38420. };
  38421. __decorate([
  38422. BABYLON.serialize()
  38423. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  38424. __decorate([
  38425. BABYLON.serialize()
  38426. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  38427. __decorate([
  38428. BABYLON.serialize()
  38429. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  38430. __decorate([
  38431. BABYLON.serialize()
  38432. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  38433. __decorate([
  38434. BABYLON.serialize()
  38435. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  38436. __decorate([
  38437. BABYLON.serialize()
  38438. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  38439. __decorate([
  38440. BABYLON.serialize()
  38441. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  38442. __decorate([
  38443. BABYLON.serialize()
  38444. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  38445. return ArcRotateCameraPointersInput;
  38446. }());
  38447. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  38448. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  38449. })(BABYLON || (BABYLON = {}));
  38450. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  38451. var BABYLON;
  38452. (function (BABYLON) {
  38453. var ArcRotateCamera = /** @class */ (function (_super) {
  38454. __extends(ArcRotateCamera, _super);
  38455. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  38456. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  38457. _this.inertialAlphaOffset = 0;
  38458. _this.inertialBetaOffset = 0;
  38459. _this.inertialRadiusOffset = 0;
  38460. _this.lowerAlphaLimit = null;
  38461. _this.upperAlphaLimit = null;
  38462. _this.lowerBetaLimit = 0.01;
  38463. _this.upperBetaLimit = Math.PI;
  38464. _this.lowerRadiusLimit = null;
  38465. _this.upperRadiusLimit = null;
  38466. _this.inertialPanningX = 0;
  38467. _this.inertialPanningY = 0;
  38468. _this.pinchToPanMaxDistance = 20;
  38469. _this.panningDistanceLimit = null;
  38470. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  38471. _this.panningInertia = 0.9;
  38472. //-- end properties for backward compatibility for inputs
  38473. _this.zoomOnFactor = 1;
  38474. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  38475. _this.allowUpsideDown = true;
  38476. _this._viewMatrix = new BABYLON.Matrix();
  38477. // Panning
  38478. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  38479. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  38480. _this.checkCollisions = false;
  38481. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  38482. _this._previousPosition = BABYLON.Vector3.Zero();
  38483. _this._collisionVelocity = BABYLON.Vector3.Zero();
  38484. _this._newPosition = BABYLON.Vector3.Zero();
  38485. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  38486. if (collidedMesh === void 0) { collidedMesh = null; }
  38487. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  38488. newPosition.multiplyInPlace(_this._collider.radius);
  38489. }
  38490. if (!collidedMesh) {
  38491. _this._previousPosition.copyFrom(_this.position);
  38492. }
  38493. else {
  38494. _this.setPosition(newPosition);
  38495. if (_this.onCollide) {
  38496. _this.onCollide(collidedMesh);
  38497. }
  38498. }
  38499. // Recompute because of constraints
  38500. var cosa = Math.cos(_this.alpha);
  38501. var sina = Math.sin(_this.alpha);
  38502. var cosb = Math.cos(_this.beta);
  38503. var sinb = Math.sin(_this.beta);
  38504. if (sinb === 0) {
  38505. sinb = 0.0001;
  38506. }
  38507. var target = _this._getTargetPosition();
  38508. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  38509. _this.position.copyFrom(_this._newPosition);
  38510. var up = _this.upVector;
  38511. if (_this.allowUpsideDown && _this.beta < 0) {
  38512. up = up.clone();
  38513. up = up.negate();
  38514. }
  38515. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  38516. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  38517. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  38518. _this._collisionTriggered = false;
  38519. };
  38520. _this._target = BABYLON.Vector3.Zero();
  38521. if (target) {
  38522. _this.setTarget(target);
  38523. }
  38524. _this.alpha = alpha;
  38525. _this.beta = beta;
  38526. _this.radius = radius;
  38527. _this.getViewMatrix();
  38528. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  38529. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  38530. return _this;
  38531. }
  38532. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  38533. get: function () {
  38534. return this._target;
  38535. },
  38536. set: function (value) {
  38537. this.setTarget(value);
  38538. },
  38539. enumerable: true,
  38540. configurable: true
  38541. });
  38542. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  38543. //-- begin properties for backward compatibility for inputs
  38544. get: function () {
  38545. var pointers = this.inputs.attached["pointers"];
  38546. if (pointers)
  38547. return pointers.angularSensibilityX;
  38548. return 0;
  38549. },
  38550. set: function (value) {
  38551. var pointers = this.inputs.attached["pointers"];
  38552. if (pointers) {
  38553. pointers.angularSensibilityX = value;
  38554. }
  38555. },
  38556. enumerable: true,
  38557. configurable: true
  38558. });
  38559. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  38560. get: function () {
  38561. var pointers = this.inputs.attached["pointers"];
  38562. if (pointers)
  38563. return pointers.angularSensibilityY;
  38564. return 0;
  38565. },
  38566. set: function (value) {
  38567. var pointers = this.inputs.attached["pointers"];
  38568. if (pointers) {
  38569. pointers.angularSensibilityY = value;
  38570. }
  38571. },
  38572. enumerable: true,
  38573. configurable: true
  38574. });
  38575. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  38576. get: function () {
  38577. var pointers = this.inputs.attached["pointers"];
  38578. if (pointers)
  38579. return pointers.pinchPrecision;
  38580. return 0;
  38581. },
  38582. set: function (value) {
  38583. var pointers = this.inputs.attached["pointers"];
  38584. if (pointers) {
  38585. pointers.pinchPrecision = value;
  38586. }
  38587. },
  38588. enumerable: true,
  38589. configurable: true
  38590. });
  38591. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  38592. get: function () {
  38593. var pointers = this.inputs.attached["pointers"];
  38594. if (pointers)
  38595. return pointers.pinchDeltaPercentage;
  38596. return 0;
  38597. },
  38598. set: function (value) {
  38599. var pointers = this.inputs.attached["pointers"];
  38600. if (pointers) {
  38601. pointers.pinchDeltaPercentage = value;
  38602. }
  38603. },
  38604. enumerable: true,
  38605. configurable: true
  38606. });
  38607. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  38608. get: function () {
  38609. var pointers = this.inputs.attached["pointers"];
  38610. if (pointers)
  38611. return pointers.panningSensibility;
  38612. return 0;
  38613. },
  38614. set: function (value) {
  38615. var pointers = this.inputs.attached["pointers"];
  38616. if (pointers) {
  38617. pointers.panningSensibility = value;
  38618. }
  38619. },
  38620. enumerable: true,
  38621. configurable: true
  38622. });
  38623. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  38624. get: function () {
  38625. var keyboard = this.inputs.attached["keyboard"];
  38626. if (keyboard)
  38627. return keyboard.keysUp;
  38628. return [];
  38629. },
  38630. set: function (value) {
  38631. var keyboard = this.inputs.attached["keyboard"];
  38632. if (keyboard)
  38633. keyboard.keysUp = value;
  38634. },
  38635. enumerable: true,
  38636. configurable: true
  38637. });
  38638. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  38639. get: function () {
  38640. var keyboard = this.inputs.attached["keyboard"];
  38641. if (keyboard)
  38642. return keyboard.keysDown;
  38643. return [];
  38644. },
  38645. set: function (value) {
  38646. var keyboard = this.inputs.attached["keyboard"];
  38647. if (keyboard)
  38648. keyboard.keysDown = value;
  38649. },
  38650. enumerable: true,
  38651. configurable: true
  38652. });
  38653. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  38654. get: function () {
  38655. var keyboard = this.inputs.attached["keyboard"];
  38656. if (keyboard)
  38657. return keyboard.keysLeft;
  38658. return [];
  38659. },
  38660. set: function (value) {
  38661. var keyboard = this.inputs.attached["keyboard"];
  38662. if (keyboard)
  38663. keyboard.keysLeft = value;
  38664. },
  38665. enumerable: true,
  38666. configurable: true
  38667. });
  38668. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  38669. get: function () {
  38670. var keyboard = this.inputs.attached["keyboard"];
  38671. if (keyboard)
  38672. return keyboard.keysRight;
  38673. return [];
  38674. },
  38675. set: function (value) {
  38676. var keyboard = this.inputs.attached["keyboard"];
  38677. if (keyboard)
  38678. keyboard.keysRight = value;
  38679. },
  38680. enumerable: true,
  38681. configurable: true
  38682. });
  38683. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  38684. get: function () {
  38685. var mousewheel = this.inputs.attached["mousewheel"];
  38686. if (mousewheel)
  38687. return mousewheel.wheelPrecision;
  38688. return 0;
  38689. },
  38690. set: function (value) {
  38691. var mousewheel = this.inputs.attached["mousewheel"];
  38692. if (mousewheel)
  38693. mousewheel.wheelPrecision = value;
  38694. },
  38695. enumerable: true,
  38696. configurable: true
  38697. });
  38698. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  38699. get: function () {
  38700. var mousewheel = this.inputs.attached["mousewheel"];
  38701. if (mousewheel)
  38702. return mousewheel.wheelDeltaPercentage;
  38703. return 0;
  38704. },
  38705. set: function (value) {
  38706. var mousewheel = this.inputs.attached["mousewheel"];
  38707. if (mousewheel)
  38708. mousewheel.wheelDeltaPercentage = value;
  38709. },
  38710. enumerable: true,
  38711. configurable: true
  38712. });
  38713. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  38714. get: function () {
  38715. return this._bouncingBehavior;
  38716. },
  38717. enumerable: true,
  38718. configurable: true
  38719. });
  38720. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  38721. get: function () {
  38722. return this._bouncingBehavior != null;
  38723. },
  38724. set: function (value) {
  38725. if (value === this.useBouncingBehavior) {
  38726. return;
  38727. }
  38728. if (value) {
  38729. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  38730. this.addBehavior(this._bouncingBehavior);
  38731. }
  38732. else if (this._bouncingBehavior) {
  38733. this.removeBehavior(this._bouncingBehavior);
  38734. this._bouncingBehavior = null;
  38735. }
  38736. },
  38737. enumerable: true,
  38738. configurable: true
  38739. });
  38740. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  38741. get: function () {
  38742. return this._framingBehavior;
  38743. },
  38744. enumerable: true,
  38745. configurable: true
  38746. });
  38747. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  38748. get: function () {
  38749. return this._framingBehavior != null;
  38750. },
  38751. set: function (value) {
  38752. if (value === this.useFramingBehavior) {
  38753. return;
  38754. }
  38755. if (value) {
  38756. this._framingBehavior = new BABYLON.FramingBehavior();
  38757. this.addBehavior(this._framingBehavior);
  38758. }
  38759. else if (this._framingBehavior) {
  38760. this.removeBehavior(this._framingBehavior);
  38761. this._framingBehavior = null;
  38762. }
  38763. },
  38764. enumerable: true,
  38765. configurable: true
  38766. });
  38767. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  38768. get: function () {
  38769. return this._autoRotationBehavior;
  38770. },
  38771. enumerable: true,
  38772. configurable: true
  38773. });
  38774. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  38775. get: function () {
  38776. return this._autoRotationBehavior != null;
  38777. },
  38778. set: function (value) {
  38779. if (value === this.useAutoRotationBehavior) {
  38780. return;
  38781. }
  38782. if (value) {
  38783. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  38784. this.addBehavior(this._autoRotationBehavior);
  38785. }
  38786. else if (this._autoRotationBehavior) {
  38787. this.removeBehavior(this._autoRotationBehavior);
  38788. this._autoRotationBehavior = null;
  38789. }
  38790. },
  38791. enumerable: true,
  38792. configurable: true
  38793. });
  38794. // Cache
  38795. ArcRotateCamera.prototype._initCache = function () {
  38796. _super.prototype._initCache.call(this);
  38797. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38798. this._cache.alpha = undefined;
  38799. this._cache.beta = undefined;
  38800. this._cache.radius = undefined;
  38801. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  38802. };
  38803. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  38804. if (!ignoreParentClass) {
  38805. _super.prototype._updateCache.call(this);
  38806. }
  38807. this._cache._target.copyFrom(this._getTargetPosition());
  38808. this._cache.alpha = this.alpha;
  38809. this._cache.beta = this.beta;
  38810. this._cache.radius = this.radius;
  38811. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  38812. };
  38813. ArcRotateCamera.prototype._getTargetPosition = function () {
  38814. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  38815. var pos = this._targetHost.getAbsolutePosition();
  38816. if (this._targetBoundingCenter) {
  38817. pos.addToRef(this._targetBoundingCenter, this._target);
  38818. }
  38819. else {
  38820. this._target.copyFrom(pos);
  38821. }
  38822. }
  38823. var lockedTargetPosition = this._getLockedTargetPosition();
  38824. if (lockedTargetPosition) {
  38825. return lockedTargetPosition;
  38826. }
  38827. return this._target;
  38828. };
  38829. ArcRotateCamera.prototype.storeState = function () {
  38830. this._storedAlpha = this.alpha;
  38831. this._storedBeta = this.beta;
  38832. this._storedRadius = this.radius;
  38833. this._storedTarget = this._getTargetPosition().clone();
  38834. return _super.prototype.storeState.call(this);
  38835. };
  38836. /**
  38837. * Restored camera state. You must call storeState() first
  38838. */
  38839. ArcRotateCamera.prototype._restoreStateValues = function () {
  38840. if (!_super.prototype._restoreStateValues.call(this)) {
  38841. return false;
  38842. }
  38843. this.alpha = this._storedAlpha;
  38844. this.beta = this._storedBeta;
  38845. this.radius = this._storedRadius;
  38846. this.setTarget(this._storedTarget.clone());
  38847. this.inertialAlphaOffset = 0;
  38848. this.inertialBetaOffset = 0;
  38849. this.inertialRadiusOffset = 0;
  38850. this.inertialPanningX = 0;
  38851. this.inertialPanningY = 0;
  38852. return true;
  38853. };
  38854. // Synchronized
  38855. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  38856. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  38857. return false;
  38858. return this._cache._target.equals(this._getTargetPosition())
  38859. && this._cache.alpha === this.alpha
  38860. && this._cache.beta === this.beta
  38861. && this._cache.radius === this.radius
  38862. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  38863. };
  38864. // Methods
  38865. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  38866. var _this = this;
  38867. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  38868. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  38869. this._useCtrlForPanning = useCtrlForPanning;
  38870. this._panningMouseButton = panningMouseButton;
  38871. this.inputs.attachElement(element, noPreventDefault);
  38872. this._reset = function () {
  38873. _this.inertialAlphaOffset = 0;
  38874. _this.inertialBetaOffset = 0;
  38875. _this.inertialRadiusOffset = 0;
  38876. _this.inertialPanningX = 0;
  38877. _this.inertialPanningY = 0;
  38878. };
  38879. };
  38880. ArcRotateCamera.prototype.detachControl = function (element) {
  38881. this.inputs.detachElement(element);
  38882. if (this._reset) {
  38883. this._reset();
  38884. }
  38885. };
  38886. ArcRotateCamera.prototype._checkInputs = function () {
  38887. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  38888. if (this._collisionTriggered) {
  38889. return;
  38890. }
  38891. this.inputs.checkInputs();
  38892. // Inertia
  38893. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  38894. if (this.getScene().useRightHandedSystem) {
  38895. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38896. }
  38897. else {
  38898. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  38899. }
  38900. this.beta += this.inertialBetaOffset;
  38901. this.radius -= this.inertialRadiusOffset;
  38902. this.inertialAlphaOffset *= this.inertia;
  38903. this.inertialBetaOffset *= this.inertia;
  38904. this.inertialRadiusOffset *= this.inertia;
  38905. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  38906. this.inertialAlphaOffset = 0;
  38907. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  38908. this.inertialBetaOffset = 0;
  38909. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  38910. this.inertialRadiusOffset = 0;
  38911. }
  38912. // Panning inertia
  38913. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  38914. if (!this._localDirection) {
  38915. this._localDirection = BABYLON.Vector3.Zero();
  38916. this._transformedDirection = BABYLON.Vector3.Zero();
  38917. }
  38918. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  38919. this._localDirection.multiplyInPlace(this.panningAxis);
  38920. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  38921. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  38922. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  38923. if (!this.panningAxis.y) {
  38924. this._transformedDirection.y = 0;
  38925. }
  38926. if (!this._targetHost) {
  38927. if (this.panningDistanceLimit) {
  38928. this._transformedDirection.addInPlace(this._target);
  38929. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  38930. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  38931. this._target.copyFrom(this._transformedDirection);
  38932. }
  38933. }
  38934. else {
  38935. this._target.addInPlace(this._transformedDirection);
  38936. }
  38937. }
  38938. this.inertialPanningX *= this.panningInertia;
  38939. this.inertialPanningY *= this.panningInertia;
  38940. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  38941. this.inertialPanningX = 0;
  38942. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  38943. this.inertialPanningY = 0;
  38944. }
  38945. // Limits
  38946. this._checkLimits();
  38947. _super.prototype._checkInputs.call(this);
  38948. };
  38949. ArcRotateCamera.prototype._checkLimits = function () {
  38950. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  38951. if (this.allowUpsideDown && this.beta > Math.PI) {
  38952. this.beta = this.beta - (2 * Math.PI);
  38953. }
  38954. }
  38955. else {
  38956. if (this.beta < this.lowerBetaLimit) {
  38957. this.beta = this.lowerBetaLimit;
  38958. }
  38959. }
  38960. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  38961. if (this.allowUpsideDown && this.beta < -Math.PI) {
  38962. this.beta = this.beta + (2 * Math.PI);
  38963. }
  38964. }
  38965. else {
  38966. if (this.beta > this.upperBetaLimit) {
  38967. this.beta = this.upperBetaLimit;
  38968. }
  38969. }
  38970. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  38971. this.alpha = this.lowerAlphaLimit;
  38972. }
  38973. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  38974. this.alpha = this.upperAlphaLimit;
  38975. }
  38976. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  38977. this.radius = this.lowerRadiusLimit;
  38978. }
  38979. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  38980. this.radius = this.upperRadiusLimit;
  38981. }
  38982. };
  38983. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  38984. var radiusv3 = this.position.subtract(this._getTargetPosition());
  38985. this.radius = radiusv3.length();
  38986. if (this.radius === 0) {
  38987. this.radius = 0.0001; // Just to avoid division by zero
  38988. }
  38989. // Alpha
  38990. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  38991. if (radiusv3.z < 0) {
  38992. this.alpha = 2 * Math.PI - this.alpha;
  38993. }
  38994. // Beta
  38995. this.beta = Math.acos(radiusv3.y / this.radius);
  38996. this._checkLimits();
  38997. };
  38998. ArcRotateCamera.prototype.setPosition = function (position) {
  38999. if (this.position.equals(position)) {
  39000. return;
  39001. }
  39002. this.position.copyFrom(position);
  39003. this.rebuildAnglesAndRadius();
  39004. };
  39005. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  39006. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  39007. if (allowSamePosition === void 0) { allowSamePosition = false; }
  39008. if (target.getBoundingInfo) {
  39009. if (toBoundingCenter) {
  39010. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  39011. }
  39012. else {
  39013. this._targetBoundingCenter = null;
  39014. }
  39015. this._targetHost = target;
  39016. this._target = this._getTargetPosition();
  39017. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  39018. }
  39019. else {
  39020. var newTarget = target;
  39021. var currentTarget = this._getTargetPosition();
  39022. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  39023. return;
  39024. }
  39025. this._targetHost = null;
  39026. this._target = newTarget;
  39027. this._targetBoundingCenter = null;
  39028. this.onMeshTargetChangedObservable.notifyObservers(null);
  39029. }
  39030. this.rebuildAnglesAndRadius();
  39031. };
  39032. ArcRotateCamera.prototype._getViewMatrix = function () {
  39033. // Compute
  39034. var cosa = Math.cos(this.alpha);
  39035. var sina = Math.sin(this.alpha);
  39036. var cosb = Math.cos(this.beta);
  39037. var sinb = Math.sin(this.beta);
  39038. if (sinb === 0) {
  39039. sinb = 0.0001;
  39040. }
  39041. var target = this._getTargetPosition();
  39042. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  39043. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  39044. if (!this._collider) {
  39045. this._collider = new BABYLON.Collider();
  39046. }
  39047. this._collider.radius = this.collisionRadius;
  39048. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  39049. this._collisionTriggered = true;
  39050. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39051. }
  39052. else {
  39053. this.position.copyFrom(this._newPosition);
  39054. var up = this.upVector;
  39055. if (this.allowUpsideDown && sinb < 0) {
  39056. up = up.clone();
  39057. up = up.negate();
  39058. }
  39059. if (this.getScene().useRightHandedSystem) {
  39060. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  39061. }
  39062. else {
  39063. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  39064. }
  39065. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  39066. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  39067. }
  39068. this._currentTarget = target;
  39069. return this._viewMatrix;
  39070. };
  39071. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  39072. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39073. meshes = meshes || this.getScene().meshes;
  39074. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  39075. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  39076. this.radius = distance * this.zoomOnFactor;
  39077. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  39078. };
  39079. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  39080. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  39081. var meshesOrMinMaxVector;
  39082. var distance;
  39083. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  39084. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  39085. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  39086. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  39087. }
  39088. else {
  39089. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  39090. meshesOrMinMaxVector = minMaxVectorAndDistance;
  39091. distance = minMaxVectorAndDistance.distance;
  39092. }
  39093. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  39094. if (!doNotUpdateMaxZ) {
  39095. this.maxZ = distance * 2;
  39096. }
  39097. };
  39098. /**
  39099. * @override
  39100. * Override Camera.createRigCamera
  39101. */
  39102. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39103. var alphaShift = 0;
  39104. switch (this.cameraRigMode) {
  39105. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39106. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39107. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39108. case BABYLON.Camera.RIG_MODE_VR:
  39109. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  39110. break;
  39111. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39112. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  39113. break;
  39114. }
  39115. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  39116. rigCam._cameraRigParams = {};
  39117. return rigCam;
  39118. };
  39119. /**
  39120. * @override
  39121. * Override Camera._updateRigCameras
  39122. */
  39123. ArcRotateCamera.prototype._updateRigCameras = function () {
  39124. var camLeft = this._rigCameras[0];
  39125. var camRight = this._rigCameras[1];
  39126. camLeft.beta = camRight.beta = this.beta;
  39127. camLeft.radius = camRight.radius = this.radius;
  39128. switch (this.cameraRigMode) {
  39129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39130. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39131. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39132. case BABYLON.Camera.RIG_MODE_VR:
  39133. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39134. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39135. break;
  39136. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39137. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  39138. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  39139. break;
  39140. }
  39141. _super.prototype._updateRigCameras.call(this);
  39142. };
  39143. ArcRotateCamera.prototype.dispose = function () {
  39144. this.inputs.clear();
  39145. _super.prototype.dispose.call(this);
  39146. };
  39147. ArcRotateCamera.prototype.getClassName = function () {
  39148. return "ArcRotateCamera";
  39149. };
  39150. __decorate([
  39151. BABYLON.serialize()
  39152. ], ArcRotateCamera.prototype, "alpha", void 0);
  39153. __decorate([
  39154. BABYLON.serialize()
  39155. ], ArcRotateCamera.prototype, "beta", void 0);
  39156. __decorate([
  39157. BABYLON.serialize()
  39158. ], ArcRotateCamera.prototype, "radius", void 0);
  39159. __decorate([
  39160. BABYLON.serializeAsVector3("target")
  39161. ], ArcRotateCamera.prototype, "_target", void 0);
  39162. __decorate([
  39163. BABYLON.serialize()
  39164. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  39165. __decorate([
  39166. BABYLON.serialize()
  39167. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  39168. __decorate([
  39169. BABYLON.serialize()
  39170. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  39171. __decorate([
  39172. BABYLON.serialize()
  39173. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  39174. __decorate([
  39175. BABYLON.serialize()
  39176. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  39177. __decorate([
  39178. BABYLON.serialize()
  39179. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  39180. __decorate([
  39181. BABYLON.serialize()
  39182. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  39183. __decorate([
  39184. BABYLON.serialize()
  39185. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  39186. __decorate([
  39187. BABYLON.serialize()
  39188. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  39189. __decorate([
  39190. BABYLON.serialize()
  39191. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  39192. __decorate([
  39193. BABYLON.serialize()
  39194. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  39195. __decorate([
  39196. BABYLON.serialize()
  39197. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  39198. __decorate([
  39199. BABYLON.serialize()
  39200. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  39201. __decorate([
  39202. BABYLON.serializeAsVector3()
  39203. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  39204. __decorate([
  39205. BABYLON.serialize()
  39206. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  39207. __decorate([
  39208. BABYLON.serialize()
  39209. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  39210. __decorate([
  39211. BABYLON.serialize()
  39212. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  39213. return ArcRotateCamera;
  39214. }(BABYLON.TargetCamera));
  39215. BABYLON.ArcRotateCamera = ArcRotateCamera;
  39216. })(BABYLON || (BABYLON = {}));
  39217. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  39218. var BABYLON;
  39219. (function (BABYLON) {
  39220. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  39221. __extends(ArcRotateCameraInputsManager, _super);
  39222. function ArcRotateCameraInputsManager(camera) {
  39223. return _super.call(this, camera) || this;
  39224. }
  39225. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  39226. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  39227. return this;
  39228. };
  39229. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  39230. this.add(new BABYLON.ArcRotateCameraPointersInput());
  39231. return this;
  39232. };
  39233. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  39234. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  39235. return this;
  39236. };
  39237. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  39238. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  39239. return this;
  39240. };
  39241. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  39242. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  39243. return this;
  39244. };
  39245. return ArcRotateCameraInputsManager;
  39246. }(BABYLON.CameraInputsManager));
  39247. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  39248. })(BABYLON || (BABYLON = {}));
  39249. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  39250. var BABYLON;
  39251. (function (BABYLON) {
  39252. var HemisphericLight = /** @class */ (function (_super) {
  39253. __extends(HemisphericLight, _super);
  39254. /**
  39255. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  39256. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  39257. * The HemisphericLight can't cast shadows.
  39258. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39259. */
  39260. function HemisphericLight(name, direction, scene) {
  39261. var _this = _super.call(this, name, scene) || this;
  39262. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  39263. _this.direction = direction || BABYLON.Vector3.Up();
  39264. return _this;
  39265. }
  39266. HemisphericLight.prototype._buildUniformLayout = function () {
  39267. this._uniformBuffer.addUniform("vLightData", 4);
  39268. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39269. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39270. this._uniformBuffer.addUniform("vLightGround", 3);
  39271. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39272. this._uniformBuffer.addUniform("depthValues", 2);
  39273. this._uniformBuffer.create();
  39274. };
  39275. /**
  39276. * Returns the string "HemisphericLight".
  39277. */
  39278. HemisphericLight.prototype.getClassName = function () {
  39279. return "HemisphericLight";
  39280. };
  39281. /**
  39282. * Sets the HemisphericLight direction towards the passed target (Vector3).
  39283. * Returns the updated direction.
  39284. */
  39285. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  39286. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  39287. return this.direction;
  39288. };
  39289. HemisphericLight.prototype.getShadowGenerator = function () {
  39290. return null;
  39291. };
  39292. /**
  39293. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  39294. * Returns the HemisphericLight.
  39295. */
  39296. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  39297. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39298. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  39299. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  39300. return this;
  39301. };
  39302. HemisphericLight.prototype._getWorldMatrix = function () {
  39303. if (!this._worldMatrix) {
  39304. this._worldMatrix = BABYLON.Matrix.Identity();
  39305. }
  39306. return this._worldMatrix;
  39307. };
  39308. /**
  39309. * Returns the integer 3.
  39310. */
  39311. HemisphericLight.prototype.getTypeID = function () {
  39312. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  39313. };
  39314. __decorate([
  39315. BABYLON.serializeAsColor3()
  39316. ], HemisphericLight.prototype, "groundColor", void 0);
  39317. __decorate([
  39318. BABYLON.serializeAsVector3()
  39319. ], HemisphericLight.prototype, "direction", void 0);
  39320. return HemisphericLight;
  39321. }(BABYLON.Light));
  39322. BABYLON.HemisphericLight = HemisphericLight;
  39323. })(BABYLON || (BABYLON = {}));
  39324. //# sourceMappingURL=babylon.hemisphericLight.js.map
  39325. var BABYLON;
  39326. (function (BABYLON) {
  39327. var ShadowLight = /** @class */ (function (_super) {
  39328. __extends(ShadowLight, _super);
  39329. function ShadowLight() {
  39330. var _this = _super !== null && _super.apply(this, arguments) || this;
  39331. _this._needProjectionMatrixCompute = true;
  39332. return _this;
  39333. }
  39334. Object.defineProperty(ShadowLight.prototype, "direction", {
  39335. get: function () {
  39336. return this._direction;
  39337. },
  39338. set: function (value) {
  39339. this._direction = value;
  39340. },
  39341. enumerable: true,
  39342. configurable: true
  39343. });
  39344. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  39345. get: function () {
  39346. return this._shadowMinZ;
  39347. },
  39348. set: function (value) {
  39349. this._shadowMinZ = value;
  39350. this.forceProjectionMatrixCompute();
  39351. },
  39352. enumerable: true,
  39353. configurable: true
  39354. });
  39355. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  39356. get: function () {
  39357. return this._shadowMaxZ;
  39358. },
  39359. set: function (value) {
  39360. this._shadowMaxZ = value;
  39361. this.forceProjectionMatrixCompute();
  39362. },
  39363. enumerable: true,
  39364. configurable: true
  39365. });
  39366. /**
  39367. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  39368. */
  39369. ShadowLight.prototype.computeTransformedInformation = function () {
  39370. if (this.parent && this.parent.getWorldMatrix) {
  39371. if (!this.transformedPosition) {
  39372. this.transformedPosition = BABYLON.Vector3.Zero();
  39373. }
  39374. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  39375. // In case the direction is present.
  39376. if (this.direction) {
  39377. if (!this.transformedDirection) {
  39378. this.transformedDirection = BABYLON.Vector3.Zero();
  39379. }
  39380. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  39381. }
  39382. return true;
  39383. }
  39384. return false;
  39385. };
  39386. /**
  39387. * Return the depth scale used for the shadow map.
  39388. */
  39389. ShadowLight.prototype.getDepthScale = function () {
  39390. return 50.0;
  39391. };
  39392. /**
  39393. * Returns the light direction (Vector3) for any passed face index.
  39394. */
  39395. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  39396. return this.transformedDirection ? this.transformedDirection : this.direction;
  39397. };
  39398. /**
  39399. * Returns the DirectionalLight absolute position in the World.
  39400. */
  39401. ShadowLight.prototype.getAbsolutePosition = function () {
  39402. return this.transformedPosition ? this.transformedPosition : this.position;
  39403. };
  39404. /**
  39405. * Sets the DirectionalLight direction toward the passed target (Vector3).
  39406. * Returns the updated DirectionalLight direction (Vector3).
  39407. */
  39408. ShadowLight.prototype.setDirectionToTarget = function (target) {
  39409. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  39410. return this.direction;
  39411. };
  39412. /**
  39413. * Returns the light rotation (Vector3).
  39414. */
  39415. ShadowLight.prototype.getRotation = function () {
  39416. this.direction.normalize();
  39417. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  39418. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  39419. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  39420. };
  39421. /**
  39422. * Boolean : false by default.
  39423. */
  39424. ShadowLight.prototype.needCube = function () {
  39425. return false;
  39426. };
  39427. /**
  39428. * Specifies wether or not the projection matrix should be recomputed this frame.
  39429. */
  39430. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  39431. return this._needProjectionMatrixCompute;
  39432. };
  39433. /**
  39434. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  39435. */
  39436. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  39437. this._needProjectionMatrixCompute = true;
  39438. };
  39439. /**
  39440. * Get the world matrix of the sahdow lights.
  39441. */
  39442. ShadowLight.prototype._getWorldMatrix = function () {
  39443. if (!this._worldMatrix) {
  39444. this._worldMatrix = BABYLON.Matrix.Identity();
  39445. }
  39446. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  39447. return this._worldMatrix;
  39448. };
  39449. /**
  39450. * Gets the minZ used for shadow according to both the scene and the light.
  39451. * @param activeCamera
  39452. */
  39453. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  39454. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  39455. };
  39456. /**
  39457. * Gets the maxZ used for shadow according to both the scene and the light.
  39458. * @param activeCamera
  39459. */
  39460. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  39461. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  39462. };
  39463. /**
  39464. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  39465. * Returns the light.
  39466. */
  39467. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39468. if (this.customProjectionMatrixBuilder) {
  39469. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  39470. }
  39471. else {
  39472. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39473. }
  39474. return this;
  39475. };
  39476. __decorate([
  39477. BABYLON.serializeAsVector3()
  39478. ], ShadowLight.prototype, "position", void 0);
  39479. __decorate([
  39480. BABYLON.serializeAsVector3()
  39481. ], ShadowLight.prototype, "direction", null);
  39482. __decorate([
  39483. BABYLON.serialize()
  39484. ], ShadowLight.prototype, "shadowMinZ", null);
  39485. __decorate([
  39486. BABYLON.serialize()
  39487. ], ShadowLight.prototype, "shadowMaxZ", null);
  39488. return ShadowLight;
  39489. }(BABYLON.Light));
  39490. BABYLON.ShadowLight = ShadowLight;
  39491. })(BABYLON || (BABYLON = {}));
  39492. //# sourceMappingURL=babylon.shadowLight.js.map
  39493. var BABYLON;
  39494. (function (BABYLON) {
  39495. var PointLight = /** @class */ (function (_super) {
  39496. __extends(PointLight, _super);
  39497. /**
  39498. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  39499. * A PointLight emits the light in every direction.
  39500. * It can cast shadows.
  39501. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  39502. * ```javascript
  39503. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  39504. * ```
  39505. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39506. */
  39507. function PointLight(name, position, scene) {
  39508. var _this = _super.call(this, name, scene) || this;
  39509. _this._shadowAngle = Math.PI / 2;
  39510. _this.position = position;
  39511. return _this;
  39512. }
  39513. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  39514. /**
  39515. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39516. * This specifies what angle the shadow will use to be created.
  39517. *
  39518. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39519. */
  39520. get: function () {
  39521. return this._shadowAngle;
  39522. },
  39523. /**
  39524. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39525. * This specifies what angle the shadow will use to be created.
  39526. *
  39527. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  39528. */
  39529. set: function (value) {
  39530. this._shadowAngle = value;
  39531. this.forceProjectionMatrixCompute();
  39532. },
  39533. enumerable: true,
  39534. configurable: true
  39535. });
  39536. Object.defineProperty(PointLight.prototype, "direction", {
  39537. get: function () {
  39538. return this._direction;
  39539. },
  39540. /**
  39541. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  39542. */
  39543. set: function (value) {
  39544. var previousNeedCube = this.needCube();
  39545. this._direction = value;
  39546. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  39547. this._shadowGenerator.recreateShadowMap();
  39548. }
  39549. },
  39550. enumerable: true,
  39551. configurable: true
  39552. });
  39553. /**
  39554. * Returns the string "PointLight"
  39555. */
  39556. PointLight.prototype.getClassName = function () {
  39557. return "PointLight";
  39558. };
  39559. /**
  39560. * Returns the integer 0.
  39561. */
  39562. PointLight.prototype.getTypeID = function () {
  39563. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  39564. };
  39565. /**
  39566. * Specifies wether or not the shadowmap should be a cube texture.
  39567. */
  39568. PointLight.prototype.needCube = function () {
  39569. return !this.direction;
  39570. };
  39571. /**
  39572. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  39573. */
  39574. PointLight.prototype.getShadowDirection = function (faceIndex) {
  39575. if (this.direction) {
  39576. return _super.prototype.getShadowDirection.call(this, faceIndex);
  39577. }
  39578. else {
  39579. switch (faceIndex) {
  39580. case 0:
  39581. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  39582. case 1:
  39583. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  39584. case 2:
  39585. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  39586. case 3:
  39587. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  39588. case 4:
  39589. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  39590. case 5:
  39591. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  39592. }
  39593. }
  39594. return BABYLON.Vector3.Zero();
  39595. };
  39596. /**
  39597. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  39598. * - fov = PI / 2
  39599. * - aspect ratio : 1.0
  39600. * - z-near and far equal to the active camera minZ and maxZ.
  39601. * Returns the PointLight.
  39602. */
  39603. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39604. var activeCamera = this.getScene().activeCamera;
  39605. if (!activeCamera) {
  39606. return;
  39607. }
  39608. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39609. };
  39610. PointLight.prototype._buildUniformLayout = function () {
  39611. this._uniformBuffer.addUniform("vLightData", 4);
  39612. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39613. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39614. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39615. this._uniformBuffer.addUniform("depthValues", 2);
  39616. this._uniformBuffer.create();
  39617. };
  39618. /**
  39619. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  39620. * Returns the PointLight.
  39621. */
  39622. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  39623. if (this.computeTransformedInformation()) {
  39624. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  39625. return this;
  39626. }
  39627. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  39628. return this;
  39629. };
  39630. __decorate([
  39631. BABYLON.serialize()
  39632. ], PointLight.prototype, "shadowAngle", null);
  39633. return PointLight;
  39634. }(BABYLON.ShadowLight));
  39635. BABYLON.PointLight = PointLight;
  39636. })(BABYLON || (BABYLON = {}));
  39637. //# sourceMappingURL=babylon.pointLight.js.map
  39638. var BABYLON;
  39639. (function (BABYLON) {
  39640. var DirectionalLight = /** @class */ (function (_super) {
  39641. __extends(DirectionalLight, _super);
  39642. /**
  39643. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  39644. * The directional light is emitted from everywhere in the given direction.
  39645. * It can cast shawdows.
  39646. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39647. */
  39648. function DirectionalLight(name, direction, scene) {
  39649. var _this = _super.call(this, name, scene) || this;
  39650. _this._shadowFrustumSize = 0;
  39651. _this._shadowOrthoScale = 0.5;
  39652. _this.autoUpdateExtends = true;
  39653. // Cache
  39654. _this._orthoLeft = Number.MAX_VALUE;
  39655. _this._orthoRight = Number.MIN_VALUE;
  39656. _this._orthoTop = Number.MIN_VALUE;
  39657. _this._orthoBottom = Number.MAX_VALUE;
  39658. _this.position = direction.scale(-1.0);
  39659. _this.direction = direction;
  39660. return _this;
  39661. }
  39662. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  39663. /**
  39664. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  39665. */
  39666. get: function () {
  39667. return this._shadowFrustumSize;
  39668. },
  39669. /**
  39670. * Specifies a fix frustum size for the shadow generation.
  39671. */
  39672. set: function (value) {
  39673. this._shadowFrustumSize = value;
  39674. this.forceProjectionMatrixCompute();
  39675. },
  39676. enumerable: true,
  39677. configurable: true
  39678. });
  39679. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  39680. get: function () {
  39681. return this._shadowOrthoScale;
  39682. },
  39683. set: function (value) {
  39684. this._shadowOrthoScale = value;
  39685. this.forceProjectionMatrixCompute();
  39686. },
  39687. enumerable: true,
  39688. configurable: true
  39689. });
  39690. /**
  39691. * Returns the string "DirectionalLight".
  39692. */
  39693. DirectionalLight.prototype.getClassName = function () {
  39694. return "DirectionalLight";
  39695. };
  39696. /**
  39697. * Returns the integer 1.
  39698. */
  39699. DirectionalLight.prototype.getTypeID = function () {
  39700. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  39701. };
  39702. /**
  39703. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  39704. * Returns the DirectionalLight Shadow projection matrix.
  39705. */
  39706. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39707. if (this.shadowFrustumSize > 0) {
  39708. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  39709. }
  39710. else {
  39711. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  39712. }
  39713. };
  39714. /**
  39715. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  39716. * Returns the DirectionalLight Shadow projection matrix.
  39717. */
  39718. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  39719. var activeCamera = this.getScene().activeCamera;
  39720. if (!activeCamera) {
  39721. return;
  39722. }
  39723. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  39724. };
  39725. /**
  39726. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  39727. * Returns the DirectionalLight Shadow projection matrix.
  39728. */
  39729. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39730. var activeCamera = this.getScene().activeCamera;
  39731. if (!activeCamera) {
  39732. return;
  39733. }
  39734. // Check extends
  39735. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  39736. var tempVector3 = BABYLON.Vector3.Zero();
  39737. this._orthoLeft = Number.MAX_VALUE;
  39738. this._orthoRight = Number.MIN_VALUE;
  39739. this._orthoTop = Number.MIN_VALUE;
  39740. this._orthoBottom = Number.MAX_VALUE;
  39741. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  39742. var mesh = renderList[meshIndex];
  39743. if (!mesh) {
  39744. continue;
  39745. }
  39746. var boundingInfo = mesh.getBoundingInfo();
  39747. if (!boundingInfo) {
  39748. continue;
  39749. }
  39750. var boundingBox = boundingInfo.boundingBox;
  39751. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  39752. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  39753. if (tempVector3.x < this._orthoLeft)
  39754. this._orthoLeft = tempVector3.x;
  39755. if (tempVector3.y < this._orthoBottom)
  39756. this._orthoBottom = tempVector3.y;
  39757. if (tempVector3.x > this._orthoRight)
  39758. this._orthoRight = tempVector3.x;
  39759. if (tempVector3.y > this._orthoTop)
  39760. this._orthoTop = tempVector3.y;
  39761. }
  39762. }
  39763. }
  39764. var xOffset = this._orthoRight - this._orthoLeft;
  39765. var yOffset = this._orthoTop - this._orthoBottom;
  39766. 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);
  39767. };
  39768. DirectionalLight.prototype._buildUniformLayout = function () {
  39769. this._uniformBuffer.addUniform("vLightData", 4);
  39770. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39771. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39772. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39773. this._uniformBuffer.addUniform("depthValues", 2);
  39774. this._uniformBuffer.create();
  39775. };
  39776. /**
  39777. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  39778. * Returns the DirectionalLight.
  39779. */
  39780. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  39781. if (this.computeTransformedInformation()) {
  39782. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  39783. return this;
  39784. }
  39785. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  39786. return this;
  39787. };
  39788. /**
  39789. * Gets the minZ used for shadow according to both the scene and the light.
  39790. *
  39791. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39792. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39793. * @param activeCamera
  39794. */
  39795. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  39796. return 1;
  39797. };
  39798. /**
  39799. * Gets the maxZ used for shadow according to both the scene and the light.
  39800. *
  39801. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  39802. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  39803. * @param activeCamera
  39804. */
  39805. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  39806. return 1;
  39807. };
  39808. __decorate([
  39809. BABYLON.serialize()
  39810. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  39811. __decorate([
  39812. BABYLON.serialize()
  39813. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  39814. __decorate([
  39815. BABYLON.serialize()
  39816. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  39817. return DirectionalLight;
  39818. }(BABYLON.ShadowLight));
  39819. BABYLON.DirectionalLight = DirectionalLight;
  39820. })(BABYLON || (BABYLON = {}));
  39821. //# sourceMappingURL=babylon.directionalLight.js.map
  39822. var BABYLON;
  39823. (function (BABYLON) {
  39824. var SpotLight = /** @class */ (function (_super) {
  39825. __extends(SpotLight, _super);
  39826. /**
  39827. * Creates a SpotLight object in the scene with the passed parameters :
  39828. * - `position` (Vector3) is the initial SpotLight position,
  39829. * - `direction` (Vector3) is the initial SpotLight direction,
  39830. * - `angle` (float, in radians) is the spot light cone angle,
  39831. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  39832. * A spot light is a simply light oriented cone.
  39833. * It can cast shadows.
  39834. * Documentation : http://doc.babylonjs.com/tutorials/lights
  39835. */
  39836. function SpotLight(name, position, direction, angle, exponent, scene) {
  39837. var _this = _super.call(this, name, scene) || this;
  39838. _this.position = position;
  39839. _this.direction = direction;
  39840. _this.angle = angle;
  39841. _this.exponent = exponent;
  39842. return _this;
  39843. }
  39844. Object.defineProperty(SpotLight.prototype, "angle", {
  39845. get: function () {
  39846. return this._angle;
  39847. },
  39848. set: function (value) {
  39849. this._angle = value;
  39850. this.forceProjectionMatrixCompute();
  39851. },
  39852. enumerable: true,
  39853. configurable: true
  39854. });
  39855. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  39856. get: function () {
  39857. return this._shadowAngleScale;
  39858. },
  39859. /**
  39860. * Allows scaling the angle of the light for shadow generation only.
  39861. */
  39862. set: function (value) {
  39863. this._shadowAngleScale = value;
  39864. this.forceProjectionMatrixCompute();
  39865. },
  39866. enumerable: true,
  39867. configurable: true
  39868. });
  39869. /**
  39870. * Returns the string "SpotLight".
  39871. */
  39872. SpotLight.prototype.getClassName = function () {
  39873. return "SpotLight";
  39874. };
  39875. /**
  39876. * Returns the integer 2.
  39877. */
  39878. SpotLight.prototype.getTypeID = function () {
  39879. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  39880. };
  39881. /**
  39882. * 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.
  39883. * Returns the SpotLight.
  39884. */
  39885. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  39886. var activeCamera = this.getScene().activeCamera;
  39887. if (!activeCamera) {
  39888. return;
  39889. }
  39890. this._shadowAngleScale = this._shadowAngleScale || 1;
  39891. var angle = this._shadowAngleScale * this._angle;
  39892. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  39893. };
  39894. SpotLight.prototype._buildUniformLayout = function () {
  39895. this._uniformBuffer.addUniform("vLightData", 4);
  39896. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  39897. this._uniformBuffer.addUniform("vLightSpecular", 3);
  39898. this._uniformBuffer.addUniform("vLightDirection", 3);
  39899. this._uniformBuffer.addUniform("shadowsInfo", 3);
  39900. this._uniformBuffer.addUniform("depthValues", 2);
  39901. this._uniformBuffer.create();
  39902. };
  39903. /**
  39904. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  39905. * Return the SpotLight.
  39906. */
  39907. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  39908. var normalizeDirection;
  39909. if (this.computeTransformedInformation()) {
  39910. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  39911. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  39912. }
  39913. else {
  39914. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  39915. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  39916. }
  39917. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  39918. return this;
  39919. };
  39920. __decorate([
  39921. BABYLON.serialize()
  39922. ], SpotLight.prototype, "angle", null);
  39923. __decorate([
  39924. BABYLON.serialize()
  39925. /**
  39926. * Allows scaling the angle of the light for shadow generation only.
  39927. */
  39928. ], SpotLight.prototype, "shadowAngleScale", null);
  39929. __decorate([
  39930. BABYLON.serialize()
  39931. ], SpotLight.prototype, "exponent", void 0);
  39932. return SpotLight;
  39933. }(BABYLON.ShadowLight));
  39934. BABYLON.SpotLight = SpotLight;
  39935. })(BABYLON || (BABYLON = {}));
  39936. //# sourceMappingURL=babylon.spotLight.js.map
  39937. var BABYLON;
  39938. (function (BABYLON) {
  39939. var AnimationRange = /** @class */ (function () {
  39940. function AnimationRange(name, from, to) {
  39941. this.name = name;
  39942. this.from = from;
  39943. this.to = to;
  39944. }
  39945. AnimationRange.prototype.clone = function () {
  39946. return new AnimationRange(this.name, this.from, this.to);
  39947. };
  39948. return AnimationRange;
  39949. }());
  39950. BABYLON.AnimationRange = AnimationRange;
  39951. /**
  39952. * Composed of a frame, and an action function
  39953. */
  39954. var AnimationEvent = /** @class */ (function () {
  39955. function AnimationEvent(frame, action, onlyOnce) {
  39956. this.frame = frame;
  39957. this.action = action;
  39958. this.onlyOnce = onlyOnce;
  39959. this.isDone = false;
  39960. }
  39961. return AnimationEvent;
  39962. }());
  39963. BABYLON.AnimationEvent = AnimationEvent;
  39964. var PathCursor = /** @class */ (function () {
  39965. function PathCursor(path) {
  39966. this.path = path;
  39967. this._onchange = new Array();
  39968. this.value = 0;
  39969. this.animations = new Array();
  39970. }
  39971. PathCursor.prototype.getPoint = function () {
  39972. var point = this.path.getPointAtLengthPosition(this.value);
  39973. return new BABYLON.Vector3(point.x, 0, point.y);
  39974. };
  39975. PathCursor.prototype.moveAhead = function (step) {
  39976. if (step === void 0) { step = 0.002; }
  39977. this.move(step);
  39978. return this;
  39979. };
  39980. PathCursor.prototype.moveBack = function (step) {
  39981. if (step === void 0) { step = 0.002; }
  39982. this.move(-step);
  39983. return this;
  39984. };
  39985. PathCursor.prototype.move = function (step) {
  39986. if (Math.abs(step) > 1) {
  39987. throw "step size should be less than 1.";
  39988. }
  39989. this.value += step;
  39990. this.ensureLimits();
  39991. this.raiseOnChange();
  39992. return this;
  39993. };
  39994. PathCursor.prototype.ensureLimits = function () {
  39995. while (this.value > 1) {
  39996. this.value -= 1;
  39997. }
  39998. while (this.value < 0) {
  39999. this.value += 1;
  40000. }
  40001. return this;
  40002. };
  40003. // used by animation engine
  40004. PathCursor.prototype.raiseOnChange = function () {
  40005. var _this = this;
  40006. this._onchange.forEach(function (f) { return f(_this); });
  40007. return this;
  40008. };
  40009. PathCursor.prototype.onchange = function (f) {
  40010. this._onchange.push(f);
  40011. return this;
  40012. };
  40013. return PathCursor;
  40014. }());
  40015. BABYLON.PathCursor = PathCursor;
  40016. var Animation = /** @class */ (function () {
  40017. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  40018. this.name = name;
  40019. this.targetProperty = targetProperty;
  40020. this.framePerSecond = framePerSecond;
  40021. this.dataType = dataType;
  40022. this.loopMode = loopMode;
  40023. this.enableBlending = enableBlending;
  40024. this._runtimeAnimations = new Array();
  40025. // The set of event that will be linked to this animation
  40026. this._events = new Array();
  40027. this.blendingSpeed = 0.01;
  40028. this._ranges = {};
  40029. this.targetPropertyPath = targetProperty.split(".");
  40030. this.dataType = dataType;
  40031. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  40032. }
  40033. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  40034. var dataType = undefined;
  40035. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  40036. dataType = Animation.ANIMATIONTYPE_FLOAT;
  40037. }
  40038. else if (from instanceof BABYLON.Quaternion) {
  40039. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  40040. }
  40041. else if (from instanceof BABYLON.Vector3) {
  40042. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  40043. }
  40044. else if (from instanceof BABYLON.Vector2) {
  40045. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  40046. }
  40047. else if (from instanceof BABYLON.Color3) {
  40048. dataType = Animation.ANIMATIONTYPE_COLOR3;
  40049. }
  40050. else if (from instanceof BABYLON.Size) {
  40051. dataType = Animation.ANIMATIONTYPE_SIZE;
  40052. }
  40053. if (dataType == undefined) {
  40054. return null;
  40055. }
  40056. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  40057. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  40058. animation.setKeys(keys);
  40059. if (easingFunction !== undefined) {
  40060. animation.setEasingFunction(easingFunction);
  40061. }
  40062. return animation;
  40063. };
  40064. /**
  40065. * Sets up an animation.
  40066. * @param property the property to animate
  40067. * @param animationType the animation type to apply
  40068. * @param easingFunction the easing function used in the animation
  40069. * @returns The created animation
  40070. */
  40071. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  40072. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  40073. animation.setEasingFunction(easingFunction);
  40074. return animation;
  40075. };
  40076. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40077. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40078. if (!animation) {
  40079. return null;
  40080. }
  40081. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40082. };
  40083. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  40084. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  40085. if (!animation) {
  40086. return null;
  40087. }
  40088. node.animations.push(animation);
  40089. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  40090. };
  40091. /**
  40092. * Transition property of the Camera to the target Value.
  40093. * @param property The property to transition
  40094. * @param targetValue The target Value of the property
  40095. * @param host The object where the property to animate belongs
  40096. * @param scene Scene used to run the animation
  40097. * @param frameRate Framerate (in frame/s) to use
  40098. * @param transition The transition type we want to use
  40099. * @param duration The duration of the animation, in milliseconds
  40100. * @param onAnimationEnd Call back trigger at the end of the animation.
  40101. */
  40102. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  40103. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  40104. if (duration <= 0) {
  40105. host[property] = targetValue;
  40106. if (onAnimationEnd) {
  40107. onAnimationEnd();
  40108. }
  40109. return null;
  40110. }
  40111. var endFrame = frameRate * (duration / 1000);
  40112. transition.setKeys([{
  40113. frame: 0,
  40114. value: host[property].clone ? host[property].clone() : host[property]
  40115. },
  40116. {
  40117. frame: endFrame,
  40118. value: targetValue
  40119. }]);
  40120. if (!host.animations) {
  40121. host.animations = [];
  40122. }
  40123. host.animations.push(transition);
  40124. var animation = scene.beginAnimation(host, 0, endFrame, false);
  40125. animation.onAnimationEnd = onAnimationEnd;
  40126. return animation;
  40127. };
  40128. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  40129. /**
  40130. * Return the array of runtime animations currently using this animation
  40131. */
  40132. get: function () {
  40133. return this._runtimeAnimations;
  40134. },
  40135. enumerable: true,
  40136. configurable: true
  40137. });
  40138. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  40139. get: function () {
  40140. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  40141. var runtimeAnimation = _a[_i];
  40142. if (!runtimeAnimation.isStopped) {
  40143. return true;
  40144. }
  40145. }
  40146. return false;
  40147. },
  40148. enumerable: true,
  40149. configurable: true
  40150. });
  40151. // Methods
  40152. /**
  40153. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  40154. */
  40155. Animation.prototype.toString = function (fullDetails) {
  40156. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  40157. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  40158. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  40159. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  40160. if (fullDetails) {
  40161. ret += ", Ranges: {";
  40162. var first = true;
  40163. for (var name in this._ranges) {
  40164. if (first) {
  40165. ret += ", ";
  40166. first = false;
  40167. }
  40168. ret += name;
  40169. }
  40170. ret += "}";
  40171. }
  40172. return ret;
  40173. };
  40174. /**
  40175. * Add an event to this animation.
  40176. */
  40177. Animation.prototype.addEvent = function (event) {
  40178. this._events.push(event);
  40179. };
  40180. /**
  40181. * Remove all events found at the given frame
  40182. * @param frame
  40183. */
  40184. Animation.prototype.removeEvents = function (frame) {
  40185. for (var index = 0; index < this._events.length; index++) {
  40186. if (this._events[index].frame === frame) {
  40187. this._events.splice(index, 1);
  40188. index--;
  40189. }
  40190. }
  40191. };
  40192. Animation.prototype.getEvents = function () {
  40193. return this._events;
  40194. };
  40195. Animation.prototype.createRange = function (name, from, to) {
  40196. // check name not already in use; could happen for bones after serialized
  40197. if (!this._ranges[name]) {
  40198. this._ranges[name] = new AnimationRange(name, from, to);
  40199. }
  40200. };
  40201. Animation.prototype.deleteRange = function (name, deleteFrames) {
  40202. if (deleteFrames === void 0) { deleteFrames = true; }
  40203. var range = this._ranges[name];
  40204. if (!range) {
  40205. return;
  40206. }
  40207. if (deleteFrames) {
  40208. var from = range.from;
  40209. var to = range.to;
  40210. // this loop MUST go high to low for multiple splices to work
  40211. for (var key = this._keys.length - 1; key >= 0; key--) {
  40212. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  40213. this._keys.splice(key, 1);
  40214. }
  40215. }
  40216. }
  40217. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  40218. };
  40219. Animation.prototype.getRange = function (name) {
  40220. return this._ranges[name];
  40221. };
  40222. Animation.prototype.getKeys = function () {
  40223. return this._keys;
  40224. };
  40225. Animation.prototype.getHighestFrame = function () {
  40226. var ret = 0;
  40227. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  40228. if (ret < this._keys[key].frame) {
  40229. ret = this._keys[key].frame;
  40230. }
  40231. }
  40232. return ret;
  40233. };
  40234. Animation.prototype.getEasingFunction = function () {
  40235. return this._easingFunction;
  40236. };
  40237. Animation.prototype.setEasingFunction = function (easingFunction) {
  40238. this._easingFunction = easingFunction;
  40239. };
  40240. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  40241. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  40242. };
  40243. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40244. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40245. };
  40246. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  40247. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  40248. };
  40249. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40250. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  40251. };
  40252. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  40253. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  40254. };
  40255. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40256. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40257. };
  40258. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  40259. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  40260. };
  40261. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  40262. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  40263. };
  40264. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  40265. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  40266. };
  40267. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  40268. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  40269. };
  40270. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  40271. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  40272. };
  40273. Animation.prototype.clone = function () {
  40274. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  40275. clone.enableBlending = this.enableBlending;
  40276. clone.blendingSpeed = this.blendingSpeed;
  40277. if (this._keys) {
  40278. clone.setKeys(this._keys);
  40279. }
  40280. if (this._ranges) {
  40281. clone._ranges = {};
  40282. for (var name in this._ranges) {
  40283. var range = this._ranges[name];
  40284. if (!range) {
  40285. continue;
  40286. }
  40287. clone._ranges[name] = range.clone();
  40288. }
  40289. }
  40290. return clone;
  40291. };
  40292. Animation.prototype.setKeys = function (values) {
  40293. this._keys = values.slice(0);
  40294. };
  40295. Animation.prototype.serialize = function () {
  40296. var serializationObject = {};
  40297. serializationObject.name = this.name;
  40298. serializationObject.property = this.targetProperty;
  40299. serializationObject.framePerSecond = this.framePerSecond;
  40300. serializationObject.dataType = this.dataType;
  40301. serializationObject.loopBehavior = this.loopMode;
  40302. serializationObject.enableBlending = this.enableBlending;
  40303. serializationObject.blendingSpeed = this.blendingSpeed;
  40304. var dataType = this.dataType;
  40305. serializationObject.keys = [];
  40306. var keys = this.getKeys();
  40307. for (var index = 0; index < keys.length; index++) {
  40308. var animationKey = keys[index];
  40309. var key = {};
  40310. key.frame = animationKey.frame;
  40311. switch (dataType) {
  40312. case Animation.ANIMATIONTYPE_FLOAT:
  40313. key.values = [animationKey.value];
  40314. break;
  40315. case Animation.ANIMATIONTYPE_QUATERNION:
  40316. case Animation.ANIMATIONTYPE_MATRIX:
  40317. case Animation.ANIMATIONTYPE_VECTOR3:
  40318. case Animation.ANIMATIONTYPE_COLOR3:
  40319. key.values = animationKey.value.asArray();
  40320. break;
  40321. }
  40322. serializationObject.keys.push(key);
  40323. }
  40324. serializationObject.ranges = [];
  40325. for (var name in this._ranges) {
  40326. var source = this._ranges[name];
  40327. if (!source) {
  40328. continue;
  40329. }
  40330. var range = {};
  40331. range.name = name;
  40332. range.from = source.from;
  40333. range.to = source.to;
  40334. serializationObject.ranges.push(range);
  40335. }
  40336. return serializationObject;
  40337. };
  40338. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  40339. get: function () {
  40340. return Animation._ANIMATIONTYPE_FLOAT;
  40341. },
  40342. enumerable: true,
  40343. configurable: true
  40344. });
  40345. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  40346. get: function () {
  40347. return Animation._ANIMATIONTYPE_VECTOR3;
  40348. },
  40349. enumerable: true,
  40350. configurable: true
  40351. });
  40352. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  40353. get: function () {
  40354. return Animation._ANIMATIONTYPE_VECTOR2;
  40355. },
  40356. enumerable: true,
  40357. configurable: true
  40358. });
  40359. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  40360. get: function () {
  40361. return Animation._ANIMATIONTYPE_SIZE;
  40362. },
  40363. enumerable: true,
  40364. configurable: true
  40365. });
  40366. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  40367. get: function () {
  40368. return Animation._ANIMATIONTYPE_QUATERNION;
  40369. },
  40370. enumerable: true,
  40371. configurable: true
  40372. });
  40373. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  40374. get: function () {
  40375. return Animation._ANIMATIONTYPE_MATRIX;
  40376. },
  40377. enumerable: true,
  40378. configurable: true
  40379. });
  40380. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  40381. get: function () {
  40382. return Animation._ANIMATIONTYPE_COLOR3;
  40383. },
  40384. enumerable: true,
  40385. configurable: true
  40386. });
  40387. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  40388. get: function () {
  40389. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  40390. },
  40391. enumerable: true,
  40392. configurable: true
  40393. });
  40394. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  40395. get: function () {
  40396. return Animation._ANIMATIONLOOPMODE_CYCLE;
  40397. },
  40398. enumerable: true,
  40399. configurable: true
  40400. });
  40401. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  40402. get: function () {
  40403. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  40404. },
  40405. enumerable: true,
  40406. configurable: true
  40407. });
  40408. Animation.Parse = function (parsedAnimation) {
  40409. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  40410. var dataType = parsedAnimation.dataType;
  40411. var keys = [];
  40412. var data;
  40413. var index;
  40414. if (parsedAnimation.enableBlending) {
  40415. animation.enableBlending = parsedAnimation.enableBlending;
  40416. }
  40417. if (parsedAnimation.blendingSpeed) {
  40418. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  40419. }
  40420. for (index = 0; index < parsedAnimation.keys.length; index++) {
  40421. var key = parsedAnimation.keys[index];
  40422. var inTangent;
  40423. var outTangent;
  40424. switch (dataType) {
  40425. case Animation.ANIMATIONTYPE_FLOAT:
  40426. data = key.values[0];
  40427. if (key.values.length >= 1) {
  40428. inTangent = key.values[1];
  40429. }
  40430. if (key.values.length >= 2) {
  40431. outTangent = key.values[2];
  40432. }
  40433. break;
  40434. case Animation.ANIMATIONTYPE_QUATERNION:
  40435. data = BABYLON.Quaternion.FromArray(key.values);
  40436. if (key.values.length >= 8) {
  40437. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  40438. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  40439. inTangent = _inTangent;
  40440. }
  40441. }
  40442. if (key.values.length >= 12) {
  40443. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  40444. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  40445. outTangent = _outTangent;
  40446. }
  40447. }
  40448. break;
  40449. case Animation.ANIMATIONTYPE_MATRIX:
  40450. data = BABYLON.Matrix.FromArray(key.values);
  40451. break;
  40452. case Animation.ANIMATIONTYPE_COLOR3:
  40453. data = BABYLON.Color3.FromArray(key.values);
  40454. break;
  40455. case Animation.ANIMATIONTYPE_VECTOR3:
  40456. default:
  40457. data = BABYLON.Vector3.FromArray(key.values);
  40458. break;
  40459. }
  40460. var keyData = {};
  40461. keyData.frame = key.frame;
  40462. keyData.value = data;
  40463. if (inTangent != undefined) {
  40464. keyData.inTangent = inTangent;
  40465. }
  40466. if (outTangent != undefined) {
  40467. keyData.outTangent = outTangent;
  40468. }
  40469. keys.push(keyData);
  40470. }
  40471. animation.setKeys(keys);
  40472. if (parsedAnimation.ranges) {
  40473. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  40474. data = parsedAnimation.ranges[index];
  40475. animation.createRange(data.name, data.from, data.to);
  40476. }
  40477. }
  40478. return animation;
  40479. };
  40480. Animation.AppendSerializedAnimations = function (source, destination) {
  40481. if (source.animations) {
  40482. destination.animations = [];
  40483. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  40484. var animation = source.animations[animationIndex];
  40485. destination.animations.push(animation.serialize());
  40486. }
  40487. }
  40488. };
  40489. Animation.AllowMatricesInterpolation = false;
  40490. // Statics
  40491. Animation._ANIMATIONTYPE_FLOAT = 0;
  40492. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  40493. Animation._ANIMATIONTYPE_QUATERNION = 2;
  40494. Animation._ANIMATIONTYPE_MATRIX = 3;
  40495. Animation._ANIMATIONTYPE_COLOR3 = 4;
  40496. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  40497. Animation._ANIMATIONTYPE_SIZE = 6;
  40498. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  40499. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  40500. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  40501. return Animation;
  40502. }());
  40503. BABYLON.Animation = Animation;
  40504. })(BABYLON || (BABYLON = {}));
  40505. //# sourceMappingURL=babylon.animation.js.map
  40506. var BABYLON;
  40507. (function (BABYLON) {
  40508. var RuntimeAnimation = /** @class */ (function () {
  40509. function RuntimeAnimation(target, animation) {
  40510. this._offsetsCache = {};
  40511. this._highLimitsCache = {};
  40512. this._stopped = false;
  40513. this._blendingFactor = 0;
  40514. this._ratioOffset = 0;
  40515. this._animation = animation;
  40516. this._target = target;
  40517. animation._runtimeAnimations.push(this);
  40518. }
  40519. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  40520. get: function () {
  40521. return this._animation;
  40522. },
  40523. enumerable: true,
  40524. configurable: true
  40525. });
  40526. RuntimeAnimation.prototype.reset = function () {
  40527. this._offsetsCache = {};
  40528. this._highLimitsCache = {};
  40529. this.currentFrame = 0;
  40530. this._blendingFactor = 0;
  40531. this._originalBlendValue = null;
  40532. };
  40533. RuntimeAnimation.prototype.isStopped = function () {
  40534. return this._stopped;
  40535. };
  40536. RuntimeAnimation.prototype.dispose = function () {
  40537. var index = this._animation.runtimeAnimations.indexOf(this);
  40538. if (index > -1) {
  40539. this._animation.runtimeAnimations.splice(index, 1);
  40540. }
  40541. };
  40542. RuntimeAnimation.prototype._getKeyValue = function (value) {
  40543. if (typeof value === "function") {
  40544. return value();
  40545. }
  40546. return value;
  40547. };
  40548. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  40549. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  40550. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  40551. }
  40552. this.currentFrame = currentFrame;
  40553. var keys = this._animation.getKeys();
  40554. // Try to get a hash to find the right key
  40555. 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));
  40556. if (keys[startKeyIndex].frame >= currentFrame) {
  40557. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  40558. startKeyIndex--;
  40559. }
  40560. }
  40561. for (var key = startKeyIndex; key < keys.length; key++) {
  40562. var endKey = keys[key + 1];
  40563. if (endKey.frame >= currentFrame) {
  40564. var startKey = keys[key];
  40565. var startValue = this._getKeyValue(startKey.value);
  40566. var endValue = this._getKeyValue(endKey.value);
  40567. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  40568. var frameDelta = endKey.frame - startKey.frame;
  40569. // gradient : percent of currentFrame between the frame inf and the frame sup
  40570. var gradient = (currentFrame - startKey.frame) / frameDelta;
  40571. // check for easingFunction and correction of gradient
  40572. var easingFunction = this._animation.getEasingFunction();
  40573. if (easingFunction != null) {
  40574. gradient = easingFunction.ease(gradient);
  40575. }
  40576. switch (this._animation.dataType) {
  40577. // Float
  40578. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40579. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  40580. switch (loopMode) {
  40581. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40582. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40583. return floatValue;
  40584. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40585. return offsetValue * repeatCount + floatValue;
  40586. }
  40587. break;
  40588. // Quaternion
  40589. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40590. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  40591. switch (loopMode) {
  40592. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40593. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40594. return quatValue;
  40595. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40596. return quatValue.add(offsetValue.scale(repeatCount));
  40597. }
  40598. return quatValue;
  40599. // Vector3
  40600. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40601. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  40602. switch (loopMode) {
  40603. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40604. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40605. return vec3Value;
  40606. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40607. return vec3Value.add(offsetValue.scale(repeatCount));
  40608. }
  40609. // Vector2
  40610. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40611. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  40612. switch (loopMode) {
  40613. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40614. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40615. return vec2Value;
  40616. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40617. return vec2Value.add(offsetValue.scale(repeatCount));
  40618. }
  40619. // Size
  40620. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40621. switch (loopMode) {
  40622. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40623. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40624. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  40625. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40626. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40627. }
  40628. // Color3
  40629. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40630. switch (loopMode) {
  40631. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40632. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40633. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  40634. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40635. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  40636. }
  40637. // Matrix
  40638. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  40639. switch (loopMode) {
  40640. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  40641. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  40642. if (BABYLON.Animation.AllowMatricesInterpolation) {
  40643. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  40644. }
  40645. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  40646. return startValue;
  40647. }
  40648. default:
  40649. break;
  40650. }
  40651. break;
  40652. }
  40653. }
  40654. return this._getKeyValue(keys[keys.length - 1].value);
  40655. };
  40656. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  40657. if (blend === void 0) { blend = false; }
  40658. // Set value
  40659. var path;
  40660. var destination;
  40661. var targetPropertyPath = this._animation.targetPropertyPath;
  40662. if (targetPropertyPath.length > 1) {
  40663. var property = this._target[targetPropertyPath[0]];
  40664. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  40665. property = property[targetPropertyPath[index]];
  40666. }
  40667. path = targetPropertyPath[targetPropertyPath.length - 1];
  40668. destination = property;
  40669. }
  40670. else {
  40671. path = targetPropertyPath[0];
  40672. destination = this._target;
  40673. }
  40674. // Blending
  40675. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  40676. if (!this._originalBlendValue) {
  40677. if (destination[path].clone) {
  40678. this._originalBlendValue = destination[path].clone();
  40679. }
  40680. else {
  40681. this._originalBlendValue = destination[path];
  40682. }
  40683. }
  40684. if (this._originalBlendValue.prototype) {
  40685. if (this._originalBlendValue.prototype.Lerp) {
  40686. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  40687. }
  40688. else {
  40689. destination[path] = currentValue;
  40690. }
  40691. }
  40692. else if (this._originalBlendValue.m) {
  40693. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  40694. }
  40695. else {
  40696. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  40697. }
  40698. this._blendingFactor += this._animation.blendingSpeed;
  40699. }
  40700. else {
  40701. destination[path] = currentValue;
  40702. }
  40703. if (this._target.markAsDirty) {
  40704. this._target.markAsDirty(this._animation.targetProperty);
  40705. }
  40706. };
  40707. RuntimeAnimation.prototype.goToFrame = function (frame) {
  40708. var keys = this._animation.getKeys();
  40709. if (frame < keys[0].frame) {
  40710. frame = keys[0].frame;
  40711. }
  40712. else if (frame > keys[keys.length - 1].frame) {
  40713. frame = keys[keys.length - 1].frame;
  40714. }
  40715. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  40716. this.setValue(currentValue);
  40717. };
  40718. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  40719. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  40720. this._ratioOffset = this._previousRatio - newRatio;
  40721. };
  40722. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  40723. if (blend === void 0) { blend = false; }
  40724. var targetPropertyPath = this._animation.targetPropertyPath;
  40725. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  40726. this._stopped = true;
  40727. return false;
  40728. }
  40729. var returnValue = true;
  40730. var keys = this._animation.getKeys();
  40731. // Adding a start key at frame 0 if missing
  40732. if (keys[0].frame !== 0) {
  40733. var newKey = { frame: 0, value: keys[0].value };
  40734. keys.splice(0, 0, newKey);
  40735. }
  40736. // Check limits
  40737. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  40738. from = keys[0].frame;
  40739. }
  40740. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  40741. to = keys[keys.length - 1].frame;
  40742. }
  40743. //to and from cannot be the same key
  40744. if (from === to) {
  40745. if (from > keys[0].frame) {
  40746. from--;
  40747. }
  40748. else if (to < keys[keys.length - 1].frame) {
  40749. to++;
  40750. }
  40751. }
  40752. // Compute ratio
  40753. var range = to - from;
  40754. var offsetValue;
  40755. // ratio represents the frame delta between from and to
  40756. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  40757. var highLimitValue = 0;
  40758. this._previousDelay = delay;
  40759. this._previousRatio = ratio;
  40760. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  40761. returnValue = false;
  40762. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  40763. }
  40764. else {
  40765. // Get max value if required
  40766. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  40767. var keyOffset = to.toString() + from.toString();
  40768. if (!this._offsetsCache[keyOffset]) {
  40769. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40770. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  40771. switch (this._animation.dataType) {
  40772. // Float
  40773. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40774. this._offsetsCache[keyOffset] = toValue - fromValue;
  40775. break;
  40776. // Quaternion
  40777. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40778. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40779. break;
  40780. // Vector3
  40781. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40782. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40783. // Vector2
  40784. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40785. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40786. // Size
  40787. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40788. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40789. // Color3
  40790. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40791. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  40792. default:
  40793. break;
  40794. }
  40795. this._highLimitsCache[keyOffset] = toValue;
  40796. }
  40797. highLimitValue = this._highLimitsCache[keyOffset];
  40798. offsetValue = this._offsetsCache[keyOffset];
  40799. }
  40800. }
  40801. if (offsetValue === undefined) {
  40802. switch (this._animation.dataType) {
  40803. // Float
  40804. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  40805. offsetValue = 0;
  40806. break;
  40807. // Quaternion
  40808. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  40809. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  40810. break;
  40811. // Vector3
  40812. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  40813. offsetValue = BABYLON.Vector3.Zero();
  40814. break;
  40815. // Vector2
  40816. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  40817. offsetValue = BABYLON.Vector2.Zero();
  40818. break;
  40819. // Size
  40820. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  40821. offsetValue = BABYLON.Size.Zero();
  40822. break;
  40823. // Color3
  40824. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  40825. offsetValue = BABYLON.Color3.Black();
  40826. }
  40827. }
  40828. // Compute value
  40829. var repeatCount = (ratio / range) >> 0;
  40830. var currentFrame = returnValue ? from + ratio % range : to;
  40831. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  40832. // Set value
  40833. this.setValue(currentValue);
  40834. // Check events
  40835. var events = this._animation.getEvents();
  40836. for (var index = 0; index < events.length; index++) {
  40837. // Make sure current frame has passed event frame and that event frame is within the current range
  40838. // Also, handle both forward and reverse animations
  40839. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  40840. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  40841. var event = events[index];
  40842. if (!event.isDone) {
  40843. // If event should be done only once, remove it.
  40844. if (event.onlyOnce) {
  40845. events.splice(index, 1);
  40846. index--;
  40847. }
  40848. event.isDone = true;
  40849. event.action();
  40850. } // Don't do anything if the event has already be done.
  40851. }
  40852. else if (events[index].isDone && !events[index].onlyOnce) {
  40853. // reset event, the animation is looping
  40854. events[index].isDone = false;
  40855. }
  40856. }
  40857. if (!returnValue) {
  40858. this._stopped = true;
  40859. }
  40860. return returnValue;
  40861. };
  40862. return RuntimeAnimation;
  40863. }());
  40864. BABYLON.RuntimeAnimation = RuntimeAnimation;
  40865. })(BABYLON || (BABYLON = {}));
  40866. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  40867. var BABYLON;
  40868. (function (BABYLON) {
  40869. var Animatable = /** @class */ (function () {
  40870. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  40871. if (fromFrame === void 0) { fromFrame = 0; }
  40872. if (toFrame === void 0) { toFrame = 100; }
  40873. if (loopAnimation === void 0) { loopAnimation = false; }
  40874. if (speedRatio === void 0) { speedRatio = 1.0; }
  40875. this.target = target;
  40876. this.fromFrame = fromFrame;
  40877. this.toFrame = toFrame;
  40878. this.loopAnimation = loopAnimation;
  40879. this.onAnimationEnd = onAnimationEnd;
  40880. this._localDelayOffset = null;
  40881. this._pausedDelay = null;
  40882. this._runtimeAnimations = new Array();
  40883. this._paused = false;
  40884. this._speedRatio = 1;
  40885. this.animationStarted = false;
  40886. if (animations) {
  40887. this.appendAnimations(target, animations);
  40888. }
  40889. this._speedRatio = speedRatio;
  40890. this._scene = scene;
  40891. scene._activeAnimatables.push(this);
  40892. }
  40893. Object.defineProperty(Animatable.prototype, "speedRatio", {
  40894. get: function () {
  40895. return this._speedRatio;
  40896. },
  40897. set: function (value) {
  40898. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  40899. var animation = this._runtimeAnimations[index];
  40900. animation._prepareForSpeedRatioChange(value);
  40901. }
  40902. this._speedRatio = value;
  40903. },
  40904. enumerable: true,
  40905. configurable: true
  40906. });
  40907. // Methods
  40908. Animatable.prototype.getAnimations = function () {
  40909. return this._runtimeAnimations;
  40910. };
  40911. Animatable.prototype.appendAnimations = function (target, animations) {
  40912. for (var index = 0; index < animations.length; index++) {
  40913. var animation = animations[index];
  40914. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  40915. }
  40916. };
  40917. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  40918. var runtimeAnimations = this._runtimeAnimations;
  40919. for (var index = 0; index < runtimeAnimations.length; index++) {
  40920. if (runtimeAnimations[index].animation.targetProperty === property) {
  40921. return runtimeAnimations[index].animation;
  40922. }
  40923. }
  40924. return null;
  40925. };
  40926. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  40927. var runtimeAnimations = this._runtimeAnimations;
  40928. for (var index = 0; index < runtimeAnimations.length; index++) {
  40929. if (runtimeAnimations[index].animation.targetProperty === property) {
  40930. return runtimeAnimations[index];
  40931. }
  40932. }
  40933. return null;
  40934. };
  40935. Animatable.prototype.reset = function () {
  40936. var runtimeAnimations = this._runtimeAnimations;
  40937. for (var index = 0; index < runtimeAnimations.length; index++) {
  40938. runtimeAnimations[index].reset();
  40939. }
  40940. this._localDelayOffset = null;
  40941. this._pausedDelay = null;
  40942. };
  40943. Animatable.prototype.enableBlending = function (blendingSpeed) {
  40944. var runtimeAnimations = this._runtimeAnimations;
  40945. for (var index = 0; index < runtimeAnimations.length; index++) {
  40946. runtimeAnimations[index].animation.enableBlending = true;
  40947. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  40948. }
  40949. };
  40950. Animatable.prototype.disableBlending = function () {
  40951. var runtimeAnimations = this._runtimeAnimations;
  40952. for (var index = 0; index < runtimeAnimations.length; index++) {
  40953. runtimeAnimations[index].animation.enableBlending = false;
  40954. }
  40955. };
  40956. Animatable.prototype.goToFrame = function (frame) {
  40957. var runtimeAnimations = this._runtimeAnimations;
  40958. if (runtimeAnimations[0]) {
  40959. var fps = runtimeAnimations[0].animation.framePerSecond;
  40960. var currentFrame = runtimeAnimations[0].currentFrame;
  40961. var adjustTime = frame - currentFrame;
  40962. var delay = adjustTime * 1000 / fps;
  40963. if (this._localDelayOffset === null) {
  40964. this._localDelayOffset = 0;
  40965. }
  40966. this._localDelayOffset -= delay;
  40967. }
  40968. for (var index = 0; index < runtimeAnimations.length; index++) {
  40969. runtimeAnimations[index].goToFrame(frame);
  40970. }
  40971. };
  40972. Animatable.prototype.pause = function () {
  40973. if (this._paused) {
  40974. return;
  40975. }
  40976. this._paused = true;
  40977. };
  40978. Animatable.prototype.restart = function () {
  40979. this._paused = false;
  40980. };
  40981. Animatable.prototype.stop = function (animationName) {
  40982. if (animationName) {
  40983. var idx = this._scene._activeAnimatables.indexOf(this);
  40984. if (idx > -1) {
  40985. var runtimeAnimations = this._runtimeAnimations;
  40986. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  40987. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  40988. continue;
  40989. }
  40990. runtimeAnimations[index].dispose();
  40991. runtimeAnimations.splice(index, 1);
  40992. }
  40993. if (runtimeAnimations.length == 0) {
  40994. this._scene._activeAnimatables.splice(idx, 1);
  40995. if (this.onAnimationEnd) {
  40996. this.onAnimationEnd();
  40997. }
  40998. }
  40999. }
  41000. }
  41001. else {
  41002. var index = this._scene._activeAnimatables.indexOf(this);
  41003. if (index > -1) {
  41004. this._scene._activeAnimatables.splice(index, 1);
  41005. var runtimeAnimations = this._runtimeAnimations;
  41006. for (var index = 0; index < runtimeAnimations.length; index++) {
  41007. runtimeAnimations[index].dispose();
  41008. }
  41009. if (this.onAnimationEnd) {
  41010. this.onAnimationEnd();
  41011. }
  41012. }
  41013. }
  41014. };
  41015. Animatable.prototype._animate = function (delay) {
  41016. if (this._paused) {
  41017. this.animationStarted = false;
  41018. if (this._pausedDelay === null) {
  41019. this._pausedDelay = delay;
  41020. }
  41021. return true;
  41022. }
  41023. if (this._localDelayOffset === null) {
  41024. this._localDelayOffset = delay;
  41025. }
  41026. else if (this._pausedDelay !== null) {
  41027. this._localDelayOffset += delay - this._pausedDelay;
  41028. this._pausedDelay = null;
  41029. }
  41030. // Animating
  41031. var running = false;
  41032. var runtimeAnimations = this._runtimeAnimations;
  41033. var index;
  41034. for (index = 0; index < runtimeAnimations.length; index++) {
  41035. var animation = runtimeAnimations[index];
  41036. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  41037. running = running || isRunning;
  41038. }
  41039. this.animationStarted = running;
  41040. if (!running) {
  41041. // Remove from active animatables
  41042. index = this._scene._activeAnimatables.indexOf(this);
  41043. this._scene._activeAnimatables.splice(index, 1);
  41044. // Dispose all runtime animations
  41045. for (index = 0; index < runtimeAnimations.length; index++) {
  41046. runtimeAnimations[index].dispose();
  41047. }
  41048. }
  41049. if (!running && this.onAnimationEnd) {
  41050. this.onAnimationEnd();
  41051. this.onAnimationEnd = null;
  41052. }
  41053. return running;
  41054. };
  41055. return Animatable;
  41056. }());
  41057. BABYLON.Animatable = Animatable;
  41058. })(BABYLON || (BABYLON = {}));
  41059. //# sourceMappingURL=babylon.animatable.js.map
  41060. var BABYLON;
  41061. (function (BABYLON) {
  41062. var EasingFunction = /** @class */ (function () {
  41063. function EasingFunction() {
  41064. // Properties
  41065. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  41066. }
  41067. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  41068. get: function () {
  41069. return EasingFunction._EASINGMODE_EASEIN;
  41070. },
  41071. enumerable: true,
  41072. configurable: true
  41073. });
  41074. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  41075. get: function () {
  41076. return EasingFunction._EASINGMODE_EASEOUT;
  41077. },
  41078. enumerable: true,
  41079. configurable: true
  41080. });
  41081. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  41082. get: function () {
  41083. return EasingFunction._EASINGMODE_EASEINOUT;
  41084. },
  41085. enumerable: true,
  41086. configurable: true
  41087. });
  41088. EasingFunction.prototype.setEasingMode = function (easingMode) {
  41089. var n = Math.min(Math.max(easingMode, 0), 2);
  41090. this._easingMode = n;
  41091. };
  41092. EasingFunction.prototype.getEasingMode = function () {
  41093. return this._easingMode;
  41094. };
  41095. EasingFunction.prototype.easeInCore = function (gradient) {
  41096. throw new Error('You must implement this method');
  41097. };
  41098. EasingFunction.prototype.ease = function (gradient) {
  41099. switch (this._easingMode) {
  41100. case EasingFunction.EASINGMODE_EASEIN:
  41101. return this.easeInCore(gradient);
  41102. case EasingFunction.EASINGMODE_EASEOUT:
  41103. return (1 - this.easeInCore(1 - gradient));
  41104. }
  41105. if (gradient >= 0.5) {
  41106. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  41107. }
  41108. return (this.easeInCore(gradient * 2) * 0.5);
  41109. };
  41110. //Statics
  41111. EasingFunction._EASINGMODE_EASEIN = 0;
  41112. EasingFunction._EASINGMODE_EASEOUT = 1;
  41113. EasingFunction._EASINGMODE_EASEINOUT = 2;
  41114. return EasingFunction;
  41115. }());
  41116. BABYLON.EasingFunction = EasingFunction;
  41117. var CircleEase = /** @class */ (function (_super) {
  41118. __extends(CircleEase, _super);
  41119. function CircleEase() {
  41120. return _super !== null && _super.apply(this, arguments) || this;
  41121. }
  41122. CircleEase.prototype.easeInCore = function (gradient) {
  41123. gradient = Math.max(0, Math.min(1, gradient));
  41124. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  41125. };
  41126. return CircleEase;
  41127. }(EasingFunction));
  41128. BABYLON.CircleEase = CircleEase;
  41129. var BackEase = /** @class */ (function (_super) {
  41130. __extends(BackEase, _super);
  41131. function BackEase(amplitude) {
  41132. if (amplitude === void 0) { amplitude = 1; }
  41133. var _this = _super.call(this) || this;
  41134. _this.amplitude = amplitude;
  41135. return _this;
  41136. }
  41137. BackEase.prototype.easeInCore = function (gradient) {
  41138. var num = Math.max(0, this.amplitude);
  41139. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  41140. };
  41141. return BackEase;
  41142. }(EasingFunction));
  41143. BABYLON.BackEase = BackEase;
  41144. var BounceEase = /** @class */ (function (_super) {
  41145. __extends(BounceEase, _super);
  41146. function BounceEase(bounces, bounciness) {
  41147. if (bounces === void 0) { bounces = 3; }
  41148. if (bounciness === void 0) { bounciness = 2; }
  41149. var _this = _super.call(this) || this;
  41150. _this.bounces = bounces;
  41151. _this.bounciness = bounciness;
  41152. return _this;
  41153. }
  41154. BounceEase.prototype.easeInCore = function (gradient) {
  41155. var y = Math.max(0.0, this.bounces);
  41156. var bounciness = this.bounciness;
  41157. if (bounciness <= 1.0) {
  41158. bounciness = 1.001;
  41159. }
  41160. var num9 = Math.pow(bounciness, y);
  41161. var num5 = 1.0 - bounciness;
  41162. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  41163. var num15 = gradient * num4;
  41164. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  41165. var num3 = Math.floor(num65);
  41166. var num13 = num3 + 1.0;
  41167. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  41168. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  41169. var num7 = (num8 + num12) * 0.5;
  41170. var num6 = gradient - num7;
  41171. var num2 = num7 - num8;
  41172. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  41173. };
  41174. return BounceEase;
  41175. }(EasingFunction));
  41176. BABYLON.BounceEase = BounceEase;
  41177. var CubicEase = /** @class */ (function (_super) {
  41178. __extends(CubicEase, _super);
  41179. function CubicEase() {
  41180. return _super !== null && _super.apply(this, arguments) || this;
  41181. }
  41182. CubicEase.prototype.easeInCore = function (gradient) {
  41183. return (gradient * gradient * gradient);
  41184. };
  41185. return CubicEase;
  41186. }(EasingFunction));
  41187. BABYLON.CubicEase = CubicEase;
  41188. var ElasticEase = /** @class */ (function (_super) {
  41189. __extends(ElasticEase, _super);
  41190. function ElasticEase(oscillations, springiness) {
  41191. if (oscillations === void 0) { oscillations = 3; }
  41192. if (springiness === void 0) { springiness = 3; }
  41193. var _this = _super.call(this) || this;
  41194. _this.oscillations = oscillations;
  41195. _this.springiness = springiness;
  41196. return _this;
  41197. }
  41198. ElasticEase.prototype.easeInCore = function (gradient) {
  41199. var num2;
  41200. var num3 = Math.max(0.0, this.oscillations);
  41201. var num = Math.max(0.0, this.springiness);
  41202. if (num == 0) {
  41203. num2 = gradient;
  41204. }
  41205. else {
  41206. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  41207. }
  41208. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  41209. };
  41210. return ElasticEase;
  41211. }(EasingFunction));
  41212. BABYLON.ElasticEase = ElasticEase;
  41213. var ExponentialEase = /** @class */ (function (_super) {
  41214. __extends(ExponentialEase, _super);
  41215. function ExponentialEase(exponent) {
  41216. if (exponent === void 0) { exponent = 2; }
  41217. var _this = _super.call(this) || this;
  41218. _this.exponent = exponent;
  41219. return _this;
  41220. }
  41221. ExponentialEase.prototype.easeInCore = function (gradient) {
  41222. if (this.exponent <= 0) {
  41223. return gradient;
  41224. }
  41225. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  41226. };
  41227. return ExponentialEase;
  41228. }(EasingFunction));
  41229. BABYLON.ExponentialEase = ExponentialEase;
  41230. var PowerEase = /** @class */ (function (_super) {
  41231. __extends(PowerEase, _super);
  41232. function PowerEase(power) {
  41233. if (power === void 0) { power = 2; }
  41234. var _this = _super.call(this) || this;
  41235. _this.power = power;
  41236. return _this;
  41237. }
  41238. PowerEase.prototype.easeInCore = function (gradient) {
  41239. var y = Math.max(0.0, this.power);
  41240. return Math.pow(gradient, y);
  41241. };
  41242. return PowerEase;
  41243. }(EasingFunction));
  41244. BABYLON.PowerEase = PowerEase;
  41245. var QuadraticEase = /** @class */ (function (_super) {
  41246. __extends(QuadraticEase, _super);
  41247. function QuadraticEase() {
  41248. return _super !== null && _super.apply(this, arguments) || this;
  41249. }
  41250. QuadraticEase.prototype.easeInCore = function (gradient) {
  41251. return (gradient * gradient);
  41252. };
  41253. return QuadraticEase;
  41254. }(EasingFunction));
  41255. BABYLON.QuadraticEase = QuadraticEase;
  41256. var QuarticEase = /** @class */ (function (_super) {
  41257. __extends(QuarticEase, _super);
  41258. function QuarticEase() {
  41259. return _super !== null && _super.apply(this, arguments) || this;
  41260. }
  41261. QuarticEase.prototype.easeInCore = function (gradient) {
  41262. return (gradient * gradient * gradient * gradient);
  41263. };
  41264. return QuarticEase;
  41265. }(EasingFunction));
  41266. BABYLON.QuarticEase = QuarticEase;
  41267. var QuinticEase = /** @class */ (function (_super) {
  41268. __extends(QuinticEase, _super);
  41269. function QuinticEase() {
  41270. return _super !== null && _super.apply(this, arguments) || this;
  41271. }
  41272. QuinticEase.prototype.easeInCore = function (gradient) {
  41273. return (gradient * gradient * gradient * gradient * gradient);
  41274. };
  41275. return QuinticEase;
  41276. }(EasingFunction));
  41277. BABYLON.QuinticEase = QuinticEase;
  41278. var SineEase = /** @class */ (function (_super) {
  41279. __extends(SineEase, _super);
  41280. function SineEase() {
  41281. return _super !== null && _super.apply(this, arguments) || this;
  41282. }
  41283. SineEase.prototype.easeInCore = function (gradient) {
  41284. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  41285. };
  41286. return SineEase;
  41287. }(EasingFunction));
  41288. BABYLON.SineEase = SineEase;
  41289. var BezierCurveEase = /** @class */ (function (_super) {
  41290. __extends(BezierCurveEase, _super);
  41291. function BezierCurveEase(x1, y1, x2, y2) {
  41292. if (x1 === void 0) { x1 = 0; }
  41293. if (y1 === void 0) { y1 = 0; }
  41294. if (x2 === void 0) { x2 = 1; }
  41295. if (y2 === void 0) { y2 = 1; }
  41296. var _this = _super.call(this) || this;
  41297. _this.x1 = x1;
  41298. _this.y1 = y1;
  41299. _this.x2 = x2;
  41300. _this.y2 = y2;
  41301. return _this;
  41302. }
  41303. BezierCurveEase.prototype.easeInCore = function (gradient) {
  41304. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  41305. };
  41306. return BezierCurveEase;
  41307. }(EasingFunction));
  41308. BABYLON.BezierCurveEase = BezierCurveEase;
  41309. })(BABYLON || (BABYLON = {}));
  41310. //# sourceMappingURL=babylon.easing.js.map
  41311. var BABYLON;
  41312. (function (BABYLON) {
  41313. var Condition = /** @class */ (function () {
  41314. function Condition(actionManager) {
  41315. this._actionManager = actionManager;
  41316. }
  41317. Condition.prototype.isValid = function () {
  41318. return true;
  41319. };
  41320. Condition.prototype._getProperty = function (propertyPath) {
  41321. return this._actionManager._getProperty(propertyPath);
  41322. };
  41323. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  41324. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41325. };
  41326. Condition.prototype.serialize = function () {
  41327. };
  41328. Condition.prototype._serialize = function (serializedCondition) {
  41329. return {
  41330. type: 2,
  41331. children: [],
  41332. name: serializedCondition.name,
  41333. properties: serializedCondition.properties
  41334. };
  41335. };
  41336. return Condition;
  41337. }());
  41338. BABYLON.Condition = Condition;
  41339. var ValueCondition = /** @class */ (function (_super) {
  41340. __extends(ValueCondition, _super);
  41341. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  41342. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  41343. var _this = _super.call(this, actionManager) || this;
  41344. _this.propertyPath = propertyPath;
  41345. _this.value = value;
  41346. _this.operator = operator;
  41347. _this._target = target;
  41348. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  41349. _this._property = _this._getProperty(_this.propertyPath);
  41350. return _this;
  41351. }
  41352. Object.defineProperty(ValueCondition, "IsEqual", {
  41353. get: function () {
  41354. return ValueCondition._IsEqual;
  41355. },
  41356. enumerable: true,
  41357. configurable: true
  41358. });
  41359. Object.defineProperty(ValueCondition, "IsDifferent", {
  41360. get: function () {
  41361. return ValueCondition._IsDifferent;
  41362. },
  41363. enumerable: true,
  41364. configurable: true
  41365. });
  41366. Object.defineProperty(ValueCondition, "IsGreater", {
  41367. get: function () {
  41368. return ValueCondition._IsGreater;
  41369. },
  41370. enumerable: true,
  41371. configurable: true
  41372. });
  41373. Object.defineProperty(ValueCondition, "IsLesser", {
  41374. get: function () {
  41375. return ValueCondition._IsLesser;
  41376. },
  41377. enumerable: true,
  41378. configurable: true
  41379. });
  41380. // Methods
  41381. ValueCondition.prototype.isValid = function () {
  41382. switch (this.operator) {
  41383. case ValueCondition.IsGreater:
  41384. return this._effectiveTarget[this._property] > this.value;
  41385. case ValueCondition.IsLesser:
  41386. return this._effectiveTarget[this._property] < this.value;
  41387. case ValueCondition.IsEqual:
  41388. case ValueCondition.IsDifferent:
  41389. var check;
  41390. if (this.value.equals) {
  41391. check = this.value.equals(this._effectiveTarget[this._property]);
  41392. }
  41393. else {
  41394. check = this.value === this._effectiveTarget[this._property];
  41395. }
  41396. return this.operator === ValueCondition.IsEqual ? check : !check;
  41397. }
  41398. return false;
  41399. };
  41400. ValueCondition.prototype.serialize = function () {
  41401. return this._serialize({
  41402. name: "ValueCondition",
  41403. properties: [
  41404. BABYLON.Action._GetTargetProperty(this._target),
  41405. { name: "propertyPath", value: this.propertyPath },
  41406. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  41407. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  41408. ]
  41409. });
  41410. };
  41411. ValueCondition.GetOperatorName = function (operator) {
  41412. switch (operator) {
  41413. case ValueCondition._IsEqual: return "IsEqual";
  41414. case ValueCondition._IsDifferent: return "IsDifferent";
  41415. case ValueCondition._IsGreater: return "IsGreater";
  41416. case ValueCondition._IsLesser: return "IsLesser";
  41417. default: return "";
  41418. }
  41419. };
  41420. // Statics
  41421. ValueCondition._IsEqual = 0;
  41422. ValueCondition._IsDifferent = 1;
  41423. ValueCondition._IsGreater = 2;
  41424. ValueCondition._IsLesser = 3;
  41425. return ValueCondition;
  41426. }(Condition));
  41427. BABYLON.ValueCondition = ValueCondition;
  41428. var PredicateCondition = /** @class */ (function (_super) {
  41429. __extends(PredicateCondition, _super);
  41430. function PredicateCondition(actionManager, predicate) {
  41431. var _this = _super.call(this, actionManager) || this;
  41432. _this.predicate = predicate;
  41433. return _this;
  41434. }
  41435. PredicateCondition.prototype.isValid = function () {
  41436. return this.predicate();
  41437. };
  41438. return PredicateCondition;
  41439. }(Condition));
  41440. BABYLON.PredicateCondition = PredicateCondition;
  41441. var StateCondition = /** @class */ (function (_super) {
  41442. __extends(StateCondition, _super);
  41443. function StateCondition(actionManager, target, value) {
  41444. var _this = _super.call(this, actionManager) || this;
  41445. _this.value = value;
  41446. _this._target = target;
  41447. return _this;
  41448. }
  41449. // Methods
  41450. StateCondition.prototype.isValid = function () {
  41451. return this._target.state === this.value;
  41452. };
  41453. StateCondition.prototype.serialize = function () {
  41454. return this._serialize({
  41455. name: "StateCondition",
  41456. properties: [
  41457. BABYLON.Action._GetTargetProperty(this._target),
  41458. { name: "value", value: this.value }
  41459. ]
  41460. });
  41461. };
  41462. return StateCondition;
  41463. }(Condition));
  41464. BABYLON.StateCondition = StateCondition;
  41465. })(BABYLON || (BABYLON = {}));
  41466. //# sourceMappingURL=babylon.condition.js.map
  41467. var BABYLON;
  41468. (function (BABYLON) {
  41469. var Action = /** @class */ (function () {
  41470. function Action(triggerOptions, condition) {
  41471. this.triggerOptions = triggerOptions;
  41472. this.onBeforeExecuteObservable = new BABYLON.Observable();
  41473. if (triggerOptions.parameter) {
  41474. this.trigger = triggerOptions.trigger;
  41475. this._triggerParameter = triggerOptions.parameter;
  41476. }
  41477. else {
  41478. this.trigger = triggerOptions;
  41479. }
  41480. this._nextActiveAction = this;
  41481. this._condition = condition;
  41482. }
  41483. // Methods
  41484. Action.prototype._prepare = function () {
  41485. };
  41486. Action.prototype.getTriggerParameter = function () {
  41487. return this._triggerParameter;
  41488. };
  41489. Action.prototype._executeCurrent = function (evt) {
  41490. if (this._nextActiveAction._condition) {
  41491. var condition = this._nextActiveAction._condition;
  41492. var currentRenderId = this._actionManager.getScene().getRenderId();
  41493. // We cache the current evaluation for the current frame
  41494. if (condition._evaluationId === currentRenderId) {
  41495. if (!condition._currentResult) {
  41496. return;
  41497. }
  41498. }
  41499. else {
  41500. condition._evaluationId = currentRenderId;
  41501. if (!condition.isValid()) {
  41502. condition._currentResult = false;
  41503. return;
  41504. }
  41505. condition._currentResult = true;
  41506. }
  41507. }
  41508. this.onBeforeExecuteObservable.notifyObservers(this);
  41509. this._nextActiveAction.execute(evt);
  41510. this.skipToNextActiveAction();
  41511. };
  41512. Action.prototype.execute = function (evt) {
  41513. };
  41514. Action.prototype.skipToNextActiveAction = function () {
  41515. if (this._nextActiveAction._child) {
  41516. if (!this._nextActiveAction._child._actionManager) {
  41517. this._nextActiveAction._child._actionManager = this._actionManager;
  41518. }
  41519. this._nextActiveAction = this._nextActiveAction._child;
  41520. }
  41521. else {
  41522. this._nextActiveAction = this;
  41523. }
  41524. };
  41525. Action.prototype.then = function (action) {
  41526. this._child = action;
  41527. action._actionManager = this._actionManager;
  41528. action._prepare();
  41529. return action;
  41530. };
  41531. Action.prototype._getProperty = function (propertyPath) {
  41532. return this._actionManager._getProperty(propertyPath);
  41533. };
  41534. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  41535. return this._actionManager._getEffectiveTarget(target, propertyPath);
  41536. };
  41537. Action.prototype.serialize = function (parent) {
  41538. };
  41539. // Called by BABYLON.Action objects in serialize(...). Internal use
  41540. Action.prototype._serialize = function (serializedAction, parent) {
  41541. var serializationObject = {
  41542. type: 1,
  41543. children: [],
  41544. name: serializedAction.name,
  41545. properties: serializedAction.properties || []
  41546. };
  41547. // Serialize child
  41548. if (this._child) {
  41549. this._child.serialize(serializationObject);
  41550. }
  41551. // Check if "this" has a condition
  41552. if (this._condition) {
  41553. var serializedCondition = this._condition.serialize();
  41554. serializedCondition.children.push(serializationObject);
  41555. if (parent) {
  41556. parent.children.push(serializedCondition);
  41557. }
  41558. return serializedCondition;
  41559. }
  41560. if (parent) {
  41561. parent.children.push(serializationObject);
  41562. }
  41563. return serializationObject;
  41564. };
  41565. Action._SerializeValueAsString = function (value) {
  41566. if (typeof value === "number") {
  41567. return value.toString();
  41568. }
  41569. if (typeof value === "boolean") {
  41570. return value ? "true" : "false";
  41571. }
  41572. if (value instanceof BABYLON.Vector2) {
  41573. return value.x + ", " + value.y;
  41574. }
  41575. if (value instanceof BABYLON.Vector3) {
  41576. return value.x + ", " + value.y + ", " + value.z;
  41577. }
  41578. if (value instanceof BABYLON.Color3) {
  41579. return value.r + ", " + value.g + ", " + value.b;
  41580. }
  41581. if (value instanceof BABYLON.Color4) {
  41582. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  41583. }
  41584. return value; // string
  41585. };
  41586. Action._GetTargetProperty = function (target) {
  41587. return {
  41588. name: "target",
  41589. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  41590. : target instanceof BABYLON.Light ? "LightProperties"
  41591. : target instanceof BABYLON.Camera ? "CameraProperties"
  41592. : "SceneProperties",
  41593. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  41594. };
  41595. };
  41596. return Action;
  41597. }());
  41598. BABYLON.Action = Action;
  41599. })(BABYLON || (BABYLON = {}));
  41600. //# sourceMappingURL=babylon.action.js.map
  41601. var BABYLON;
  41602. (function (BABYLON) {
  41603. /**
  41604. * ActionEvent is the event beint sent when an action is triggered.
  41605. */
  41606. var ActionEvent = /** @class */ (function () {
  41607. /**
  41608. * @param source The mesh or sprite that triggered the action.
  41609. * @param pointerX The X mouse cursor position at the time of the event
  41610. * @param pointerY The Y mouse cursor position at the time of the event
  41611. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  41612. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  41613. */
  41614. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  41615. this.source = source;
  41616. this.pointerX = pointerX;
  41617. this.pointerY = pointerY;
  41618. this.meshUnderPointer = meshUnderPointer;
  41619. this.sourceEvent = sourceEvent;
  41620. this.additionalData = additionalData;
  41621. }
  41622. /**
  41623. * Helper function to auto-create an ActionEvent from a source mesh.
  41624. * @param source The source mesh that triggered the event
  41625. * @param evt {Event} The original (browser) event
  41626. */
  41627. ActionEvent.CreateNew = function (source, evt, additionalData) {
  41628. var scene = source.getScene();
  41629. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41630. };
  41631. /**
  41632. * Helper function to auto-create an ActionEvent from a source mesh.
  41633. * @param source The source sprite that triggered the event
  41634. * @param scene Scene associated with the sprite
  41635. * @param evt {Event} The original (browser) event
  41636. */
  41637. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  41638. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  41639. };
  41640. /**
  41641. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  41642. * @param scene the scene where the event occurred
  41643. * @param evt {Event} The original (browser) event
  41644. */
  41645. ActionEvent.CreateNewFromScene = function (scene, evt) {
  41646. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  41647. };
  41648. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  41649. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  41650. };
  41651. return ActionEvent;
  41652. }());
  41653. BABYLON.ActionEvent = ActionEvent;
  41654. /**
  41655. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  41656. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  41657. */
  41658. var ActionManager = /** @class */ (function () {
  41659. function ActionManager(scene) {
  41660. // Members
  41661. this.actions = new Array();
  41662. this.hoverCursor = '';
  41663. this._scene = scene;
  41664. scene._actionManagers.push(this);
  41665. }
  41666. Object.defineProperty(ActionManager, "NothingTrigger", {
  41667. get: function () {
  41668. return ActionManager._NothingTrigger;
  41669. },
  41670. enumerable: true,
  41671. configurable: true
  41672. });
  41673. Object.defineProperty(ActionManager, "OnPickTrigger", {
  41674. get: function () {
  41675. return ActionManager._OnPickTrigger;
  41676. },
  41677. enumerable: true,
  41678. configurable: true
  41679. });
  41680. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  41681. get: function () {
  41682. return ActionManager._OnLeftPickTrigger;
  41683. },
  41684. enumerable: true,
  41685. configurable: true
  41686. });
  41687. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  41688. get: function () {
  41689. return ActionManager._OnRightPickTrigger;
  41690. },
  41691. enumerable: true,
  41692. configurable: true
  41693. });
  41694. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  41695. get: function () {
  41696. return ActionManager._OnCenterPickTrigger;
  41697. },
  41698. enumerable: true,
  41699. configurable: true
  41700. });
  41701. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  41702. get: function () {
  41703. return ActionManager._OnPickDownTrigger;
  41704. },
  41705. enumerable: true,
  41706. configurable: true
  41707. });
  41708. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  41709. get: function () {
  41710. return ActionManager._OnDoublePickTrigger;
  41711. },
  41712. enumerable: true,
  41713. configurable: true
  41714. });
  41715. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  41716. get: function () {
  41717. return ActionManager._OnPickUpTrigger;
  41718. },
  41719. enumerable: true,
  41720. configurable: true
  41721. });
  41722. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  41723. /// This trigger will only be raised if you also declared a OnPickDown
  41724. get: function () {
  41725. return ActionManager._OnPickOutTrigger;
  41726. },
  41727. enumerable: true,
  41728. configurable: true
  41729. });
  41730. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  41731. get: function () {
  41732. return ActionManager._OnLongPressTrigger;
  41733. },
  41734. enumerable: true,
  41735. configurable: true
  41736. });
  41737. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  41738. get: function () {
  41739. return ActionManager._OnPointerOverTrigger;
  41740. },
  41741. enumerable: true,
  41742. configurable: true
  41743. });
  41744. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  41745. get: function () {
  41746. return ActionManager._OnPointerOutTrigger;
  41747. },
  41748. enumerable: true,
  41749. configurable: true
  41750. });
  41751. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  41752. get: function () {
  41753. return ActionManager._OnEveryFrameTrigger;
  41754. },
  41755. enumerable: true,
  41756. configurable: true
  41757. });
  41758. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  41759. get: function () {
  41760. return ActionManager._OnIntersectionEnterTrigger;
  41761. },
  41762. enumerable: true,
  41763. configurable: true
  41764. });
  41765. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  41766. get: function () {
  41767. return ActionManager._OnIntersectionExitTrigger;
  41768. },
  41769. enumerable: true,
  41770. configurable: true
  41771. });
  41772. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  41773. get: function () {
  41774. return ActionManager._OnKeyDownTrigger;
  41775. },
  41776. enumerable: true,
  41777. configurable: true
  41778. });
  41779. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  41780. get: function () {
  41781. return ActionManager._OnKeyUpTrigger;
  41782. },
  41783. enumerable: true,
  41784. configurable: true
  41785. });
  41786. // Methods
  41787. ActionManager.prototype.dispose = function () {
  41788. var index = this._scene._actionManagers.indexOf(this);
  41789. for (var i = 0; i < this.actions.length; i++) {
  41790. var action = this.actions[i];
  41791. ActionManager.Triggers[action.trigger]--;
  41792. if (ActionManager.Triggers[action.trigger] === 0) {
  41793. delete ActionManager.Triggers[action.trigger];
  41794. }
  41795. }
  41796. if (index > -1) {
  41797. this._scene._actionManagers.splice(index, 1);
  41798. }
  41799. };
  41800. ActionManager.prototype.getScene = function () {
  41801. return this._scene;
  41802. };
  41803. /**
  41804. * Does this action manager handles actions of any of the given triggers
  41805. * @param {number[]} triggers - the triggers to be tested
  41806. * @return {boolean} whether one (or more) of the triggers is handeled
  41807. */
  41808. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  41809. for (var index = 0; index < this.actions.length; index++) {
  41810. var action = this.actions[index];
  41811. if (triggers.indexOf(action.trigger) > -1) {
  41812. return true;
  41813. }
  41814. }
  41815. return false;
  41816. };
  41817. /**
  41818. * Does this action manager handles actions of a given trigger
  41819. * @param {number} trigger - the trigger to be tested
  41820. * @return {boolean} whether the trigger is handeled
  41821. */
  41822. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  41823. for (var index = 0; index < this.actions.length; index++) {
  41824. var action = this.actions[index];
  41825. if (action.trigger === trigger) {
  41826. return true;
  41827. }
  41828. }
  41829. return false;
  41830. };
  41831. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  41832. /**
  41833. * Does this action manager has pointer triggers
  41834. * @return {boolean} whether or not it has pointer triggers
  41835. */
  41836. get: function () {
  41837. for (var index = 0; index < this.actions.length; index++) {
  41838. var action = this.actions[index];
  41839. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  41840. return true;
  41841. }
  41842. }
  41843. return false;
  41844. },
  41845. enumerable: true,
  41846. configurable: true
  41847. });
  41848. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  41849. /**
  41850. * Does this action manager has pick triggers
  41851. * @return {boolean} whether or not it has pick triggers
  41852. */
  41853. get: function () {
  41854. for (var index = 0; index < this.actions.length; index++) {
  41855. var action = this.actions[index];
  41856. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  41857. return true;
  41858. }
  41859. }
  41860. return false;
  41861. },
  41862. enumerable: true,
  41863. configurable: true
  41864. });
  41865. Object.defineProperty(ActionManager, "HasTriggers", {
  41866. /**
  41867. * Does exist one action manager with at least one trigger
  41868. * @return {boolean} whether or not it exists one action manager with one trigger
  41869. **/
  41870. get: function () {
  41871. for (var t in ActionManager.Triggers) {
  41872. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41873. return true;
  41874. }
  41875. }
  41876. return false;
  41877. },
  41878. enumerable: true,
  41879. configurable: true
  41880. });
  41881. Object.defineProperty(ActionManager, "HasPickTriggers", {
  41882. /**
  41883. * Does exist one action manager with at least one pick trigger
  41884. * @return {boolean} whether or not it exists one action manager with one pick trigger
  41885. **/
  41886. get: function () {
  41887. for (var t in ActionManager.Triggers) {
  41888. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41889. var t_int = parseInt(t);
  41890. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  41891. return true;
  41892. }
  41893. }
  41894. }
  41895. return false;
  41896. },
  41897. enumerable: true,
  41898. configurable: true
  41899. });
  41900. /**
  41901. * Does exist one action manager that handles actions of a given trigger
  41902. * @param {number} trigger - the trigger to be tested
  41903. * @return {boolean} whether the trigger is handeled by at least one action manager
  41904. **/
  41905. ActionManager.HasSpecificTrigger = function (trigger) {
  41906. for (var t in ActionManager.Triggers) {
  41907. if (ActionManager.Triggers.hasOwnProperty(t)) {
  41908. var t_int = parseInt(t);
  41909. if (t_int === trigger) {
  41910. return true;
  41911. }
  41912. }
  41913. }
  41914. return false;
  41915. };
  41916. /**
  41917. * Registers an action to this action manager
  41918. * @param {BABYLON.Action} action - the action to be registered
  41919. * @return {BABYLON.Action} the action amended (prepared) after registration
  41920. */
  41921. ActionManager.prototype.registerAction = function (action) {
  41922. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  41923. if (this.getScene().actionManager !== this) {
  41924. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  41925. return null;
  41926. }
  41927. }
  41928. this.actions.push(action);
  41929. if (ActionManager.Triggers[action.trigger]) {
  41930. ActionManager.Triggers[action.trigger]++;
  41931. }
  41932. else {
  41933. ActionManager.Triggers[action.trigger] = 1;
  41934. }
  41935. action._actionManager = this;
  41936. action._prepare();
  41937. return action;
  41938. };
  41939. /**
  41940. * Process a specific trigger
  41941. * @param {number} trigger - the trigger to process
  41942. * @param evt {BABYLON.ActionEvent} the event details to be processed
  41943. */
  41944. ActionManager.prototype.processTrigger = function (trigger, evt) {
  41945. for (var index = 0; index < this.actions.length; index++) {
  41946. var action = this.actions[index];
  41947. if (action.trigger === trigger) {
  41948. if (evt) {
  41949. if (trigger === ActionManager.OnKeyUpTrigger
  41950. || trigger === ActionManager.OnKeyDownTrigger) {
  41951. var parameter = action.getTriggerParameter();
  41952. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  41953. if (!parameter.toLowerCase) {
  41954. continue;
  41955. }
  41956. var lowerCase = parameter.toLowerCase();
  41957. if (lowerCase !== evt.sourceEvent.key) {
  41958. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  41959. var actualkey = String.fromCharCode(unicode).toLowerCase();
  41960. if (actualkey !== lowerCase) {
  41961. continue;
  41962. }
  41963. }
  41964. }
  41965. }
  41966. }
  41967. action._executeCurrent(evt);
  41968. }
  41969. }
  41970. };
  41971. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  41972. var properties = propertyPath.split(".");
  41973. for (var index = 0; index < properties.length - 1; index++) {
  41974. target = target[properties[index]];
  41975. }
  41976. return target;
  41977. };
  41978. ActionManager.prototype._getProperty = function (propertyPath) {
  41979. var properties = propertyPath.split(".");
  41980. return properties[properties.length - 1];
  41981. };
  41982. ActionManager.prototype.serialize = function (name) {
  41983. var root = {
  41984. children: new Array(),
  41985. name: name,
  41986. type: 3,
  41987. properties: new Array() // Empty for root but required
  41988. };
  41989. for (var i = 0; i < this.actions.length; i++) {
  41990. var triggerObject = {
  41991. type: 0,
  41992. children: new Array(),
  41993. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  41994. properties: new Array()
  41995. };
  41996. var triggerOptions = this.actions[i].triggerOptions;
  41997. if (triggerOptions && typeof triggerOptions !== "number") {
  41998. if (triggerOptions.parameter instanceof BABYLON.Node) {
  41999. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  42000. }
  42001. else {
  42002. var parameter = {};
  42003. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  42004. if (triggerOptions.parameter.mesh) {
  42005. parameter._meshId = triggerOptions.parameter.mesh.id;
  42006. }
  42007. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  42008. }
  42009. }
  42010. // Serialize child action, recursively
  42011. this.actions[i].serialize(triggerObject);
  42012. // Add serialized trigger
  42013. root.children.push(triggerObject);
  42014. }
  42015. return root;
  42016. };
  42017. ActionManager.Parse = function (parsedActions, object, scene) {
  42018. var actionManager = new BABYLON.ActionManager(scene);
  42019. if (object === null)
  42020. scene.actionManager = actionManager;
  42021. else
  42022. object.actionManager = actionManager;
  42023. // instanciate a new object
  42024. var instanciate = function (name, params) {
  42025. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  42026. newInstance.constructor.apply(newInstance, params);
  42027. return newInstance;
  42028. };
  42029. var parseParameter = function (name, value, target, propertyPath) {
  42030. if (propertyPath === null) {
  42031. // String, boolean or float
  42032. var floatValue = parseFloat(value);
  42033. if (value === "true" || value === "false")
  42034. return value === "true";
  42035. else
  42036. return isNaN(floatValue) ? value : floatValue;
  42037. }
  42038. var effectiveTarget = propertyPath.split(".");
  42039. var values = value.split(",");
  42040. // Get effective Target
  42041. for (var i = 0; i < effectiveTarget.length; i++) {
  42042. target = target[effectiveTarget[i]];
  42043. }
  42044. // Return appropriate value with its type
  42045. if (typeof (target) === "boolean")
  42046. return values[0] === "true";
  42047. if (typeof (target) === "string")
  42048. return values[0];
  42049. // Parameters with multiple values such as Vector3 etc.
  42050. var split = new Array();
  42051. for (var i = 0; i < values.length; i++)
  42052. split.push(parseFloat(values[i]));
  42053. if (target instanceof BABYLON.Vector3)
  42054. return BABYLON.Vector3.FromArray(split);
  42055. if (target instanceof BABYLON.Vector4)
  42056. return BABYLON.Vector4.FromArray(split);
  42057. if (target instanceof BABYLON.Color3)
  42058. return BABYLON.Color3.FromArray(split);
  42059. if (target instanceof BABYLON.Color4)
  42060. return BABYLON.Color4.FromArray(split);
  42061. return parseFloat(values[0]);
  42062. };
  42063. // traverse graph per trigger
  42064. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  42065. if (combineArray === void 0) { combineArray = null; }
  42066. if (parsedAction.detached)
  42067. return;
  42068. var parameters = new Array();
  42069. var target = null;
  42070. var propertyPath = null;
  42071. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  42072. // Parameters
  42073. if (parsedAction.type === 2)
  42074. parameters.push(actionManager);
  42075. else
  42076. parameters.push(trigger);
  42077. if (combine) {
  42078. var actions = new Array();
  42079. for (var j = 0; j < parsedAction.combine.length; j++) {
  42080. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  42081. }
  42082. parameters.push(actions);
  42083. }
  42084. else {
  42085. for (var i = 0; i < parsedAction.properties.length; i++) {
  42086. var value = parsedAction.properties[i].value;
  42087. var name = parsedAction.properties[i].name;
  42088. var targetType = parsedAction.properties[i].targetType;
  42089. if (name === "target")
  42090. if (targetType !== null && targetType === "SceneProperties")
  42091. value = target = scene;
  42092. else
  42093. value = target = scene.getNodeByName(value);
  42094. else if (name === "parent")
  42095. value = scene.getNodeByName(value);
  42096. else if (name === "sound")
  42097. value = scene.getSoundByName(value);
  42098. else if (name !== "propertyPath") {
  42099. if (parsedAction.type === 2 && name === "operator")
  42100. value = BABYLON.ValueCondition[value];
  42101. else
  42102. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  42103. }
  42104. else {
  42105. propertyPath = value;
  42106. }
  42107. parameters.push(value);
  42108. }
  42109. }
  42110. if (combineArray === null) {
  42111. parameters.push(condition);
  42112. }
  42113. else {
  42114. parameters.push(null);
  42115. }
  42116. // If interpolate value action
  42117. if (parsedAction.name === "InterpolateValueAction") {
  42118. var param = parameters[parameters.length - 2];
  42119. parameters[parameters.length - 1] = param;
  42120. parameters[parameters.length - 2] = condition;
  42121. }
  42122. // Action or condition(s) and not CombineAction
  42123. var newAction = instanciate(parsedAction.name, parameters);
  42124. if (newAction instanceof BABYLON.Condition && condition !== null) {
  42125. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  42126. if (action)
  42127. action.then(nothing);
  42128. else
  42129. actionManager.registerAction(nothing);
  42130. action = nothing;
  42131. }
  42132. if (combineArray === null) {
  42133. if (newAction instanceof BABYLON.Condition) {
  42134. condition = newAction;
  42135. newAction = action;
  42136. }
  42137. else {
  42138. condition = null;
  42139. if (action)
  42140. action.then(newAction);
  42141. else
  42142. actionManager.registerAction(newAction);
  42143. }
  42144. }
  42145. else {
  42146. combineArray.push(newAction);
  42147. }
  42148. for (var i = 0; i < parsedAction.children.length; i++)
  42149. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  42150. };
  42151. // triggers
  42152. for (var i = 0; i < parsedActions.children.length; i++) {
  42153. var triggerParams;
  42154. var trigger = parsedActions.children[i];
  42155. if (trigger.properties.length > 0) {
  42156. var param = trigger.properties[0].value;
  42157. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  42158. if (value._meshId) {
  42159. value.mesh = scene.getMeshByID(value._meshId);
  42160. }
  42161. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  42162. }
  42163. else
  42164. triggerParams = ActionManager[trigger.name];
  42165. for (var j = 0; j < trigger.children.length; j++) {
  42166. if (!trigger.detached)
  42167. traverse(trigger.children[j], triggerParams, null, null);
  42168. }
  42169. }
  42170. };
  42171. ActionManager.GetTriggerName = function (trigger) {
  42172. switch (trigger) {
  42173. case 0: return "NothingTrigger";
  42174. case 1: return "OnPickTrigger";
  42175. case 2: return "OnLeftPickTrigger";
  42176. case 3: return "OnRightPickTrigger";
  42177. case 4: return "OnCenterPickTrigger";
  42178. case 5: return "OnPickDownTrigger";
  42179. case 6: return "OnPickUpTrigger";
  42180. case 7: return "OnLongPressTrigger";
  42181. case 8: return "OnPointerOverTrigger";
  42182. case 9: return "OnPointerOutTrigger";
  42183. case 10: return "OnEveryFrameTrigger";
  42184. case 11: return "OnIntersectionEnterTrigger";
  42185. case 12: return "OnIntersectionExitTrigger";
  42186. case 13: return "OnKeyDownTrigger";
  42187. case 14: return "OnKeyUpTrigger";
  42188. case 15: return "OnPickOutTrigger";
  42189. default: return "";
  42190. }
  42191. };
  42192. // Statics
  42193. ActionManager._NothingTrigger = 0;
  42194. ActionManager._OnPickTrigger = 1;
  42195. ActionManager._OnLeftPickTrigger = 2;
  42196. ActionManager._OnRightPickTrigger = 3;
  42197. ActionManager._OnCenterPickTrigger = 4;
  42198. ActionManager._OnPickDownTrigger = 5;
  42199. ActionManager._OnDoublePickTrigger = 6;
  42200. ActionManager._OnPickUpTrigger = 7;
  42201. ActionManager._OnLongPressTrigger = 8;
  42202. ActionManager._OnPointerOverTrigger = 9;
  42203. ActionManager._OnPointerOutTrigger = 10;
  42204. ActionManager._OnEveryFrameTrigger = 11;
  42205. ActionManager._OnIntersectionEnterTrigger = 12;
  42206. ActionManager._OnIntersectionExitTrigger = 13;
  42207. ActionManager._OnKeyDownTrigger = 14;
  42208. ActionManager._OnKeyUpTrigger = 15;
  42209. ActionManager._OnPickOutTrigger = 16;
  42210. ActionManager.Triggers = {};
  42211. return ActionManager;
  42212. }());
  42213. BABYLON.ActionManager = ActionManager;
  42214. })(BABYLON || (BABYLON = {}));
  42215. //# sourceMappingURL=babylon.actionManager.js.map
  42216. var BABYLON;
  42217. (function (BABYLON) {
  42218. var InterpolateValueAction = /** @class */ (function (_super) {
  42219. __extends(InterpolateValueAction, _super);
  42220. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  42221. if (duration === void 0) { duration = 1000; }
  42222. var _this = _super.call(this, triggerOptions, condition) || this;
  42223. _this.propertyPath = propertyPath;
  42224. _this.value = value;
  42225. _this.duration = duration;
  42226. _this.stopOtherAnimations = stopOtherAnimations;
  42227. _this.onInterpolationDone = onInterpolationDone;
  42228. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  42229. _this._target = _this._effectiveTarget = target;
  42230. return _this;
  42231. }
  42232. InterpolateValueAction.prototype._prepare = function () {
  42233. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42234. this._property = this._getProperty(this.propertyPath);
  42235. };
  42236. InterpolateValueAction.prototype.execute = function () {
  42237. var _this = this;
  42238. var scene = this._actionManager.getScene();
  42239. var keys = [
  42240. {
  42241. frame: 0,
  42242. value: this._effectiveTarget[this._property]
  42243. }, {
  42244. frame: 100,
  42245. value: this.value
  42246. }
  42247. ];
  42248. var dataType;
  42249. if (typeof this.value === "number") {
  42250. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  42251. }
  42252. else if (this.value instanceof BABYLON.Color3) {
  42253. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  42254. }
  42255. else if (this.value instanceof BABYLON.Vector3) {
  42256. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  42257. }
  42258. else if (this.value instanceof BABYLON.Matrix) {
  42259. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  42260. }
  42261. else if (this.value instanceof BABYLON.Quaternion) {
  42262. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  42263. }
  42264. else {
  42265. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  42266. return;
  42267. }
  42268. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  42269. animation.setKeys(keys);
  42270. if (this.stopOtherAnimations) {
  42271. scene.stopAnimation(this._effectiveTarget);
  42272. }
  42273. var wrapper = function () {
  42274. _this.onInterpolationDoneObservable.notifyObservers(_this);
  42275. if (_this.onInterpolationDone) {
  42276. _this.onInterpolationDone();
  42277. }
  42278. };
  42279. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  42280. };
  42281. InterpolateValueAction.prototype.serialize = function (parent) {
  42282. return _super.prototype._serialize.call(this, {
  42283. name: "InterpolateValueAction",
  42284. properties: [
  42285. BABYLON.Action._GetTargetProperty(this._target),
  42286. { name: "propertyPath", value: this.propertyPath },
  42287. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  42288. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  42289. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  42290. ]
  42291. }, parent);
  42292. };
  42293. return InterpolateValueAction;
  42294. }(BABYLON.Action));
  42295. BABYLON.InterpolateValueAction = InterpolateValueAction;
  42296. })(BABYLON || (BABYLON = {}));
  42297. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  42298. var BABYLON;
  42299. (function (BABYLON) {
  42300. var SwitchBooleanAction = /** @class */ (function (_super) {
  42301. __extends(SwitchBooleanAction, _super);
  42302. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  42303. var _this = _super.call(this, triggerOptions, condition) || this;
  42304. _this.propertyPath = propertyPath;
  42305. _this._target = _this._effectiveTarget = target;
  42306. return _this;
  42307. }
  42308. SwitchBooleanAction.prototype._prepare = function () {
  42309. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42310. this._property = this._getProperty(this.propertyPath);
  42311. };
  42312. SwitchBooleanAction.prototype.execute = function () {
  42313. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  42314. };
  42315. SwitchBooleanAction.prototype.serialize = function (parent) {
  42316. return _super.prototype._serialize.call(this, {
  42317. name: "SwitchBooleanAction",
  42318. properties: [
  42319. BABYLON.Action._GetTargetProperty(this._target),
  42320. { name: "propertyPath", value: this.propertyPath }
  42321. ]
  42322. }, parent);
  42323. };
  42324. return SwitchBooleanAction;
  42325. }(BABYLON.Action));
  42326. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  42327. var SetStateAction = /** @class */ (function (_super) {
  42328. __extends(SetStateAction, _super);
  42329. function SetStateAction(triggerOptions, target, value, condition) {
  42330. var _this = _super.call(this, triggerOptions, condition) || this;
  42331. _this.value = value;
  42332. _this._target = target;
  42333. return _this;
  42334. }
  42335. SetStateAction.prototype.execute = function () {
  42336. this._target.state = this.value;
  42337. };
  42338. SetStateAction.prototype.serialize = function (parent) {
  42339. return _super.prototype._serialize.call(this, {
  42340. name: "SetStateAction",
  42341. properties: [
  42342. BABYLON.Action._GetTargetProperty(this._target),
  42343. { name: "value", value: this.value }
  42344. ]
  42345. }, parent);
  42346. };
  42347. return SetStateAction;
  42348. }(BABYLON.Action));
  42349. BABYLON.SetStateAction = SetStateAction;
  42350. var SetValueAction = /** @class */ (function (_super) {
  42351. __extends(SetValueAction, _super);
  42352. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  42353. var _this = _super.call(this, triggerOptions, condition) || this;
  42354. _this.propertyPath = propertyPath;
  42355. _this.value = value;
  42356. _this._target = _this._effectiveTarget = target;
  42357. return _this;
  42358. }
  42359. SetValueAction.prototype._prepare = function () {
  42360. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42361. this._property = this._getProperty(this.propertyPath);
  42362. };
  42363. SetValueAction.prototype.execute = function () {
  42364. this._effectiveTarget[this._property] = this.value;
  42365. if (this._target.markAsDirty) {
  42366. this._target.markAsDirty(this._property);
  42367. }
  42368. };
  42369. SetValueAction.prototype.serialize = function (parent) {
  42370. return _super.prototype._serialize.call(this, {
  42371. name: "SetValueAction",
  42372. properties: [
  42373. BABYLON.Action._GetTargetProperty(this._target),
  42374. { name: "propertyPath", value: this.propertyPath },
  42375. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42376. ]
  42377. }, parent);
  42378. };
  42379. return SetValueAction;
  42380. }(BABYLON.Action));
  42381. BABYLON.SetValueAction = SetValueAction;
  42382. var IncrementValueAction = /** @class */ (function (_super) {
  42383. __extends(IncrementValueAction, _super);
  42384. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  42385. var _this = _super.call(this, triggerOptions, condition) || this;
  42386. _this.propertyPath = propertyPath;
  42387. _this.value = value;
  42388. _this._target = _this._effectiveTarget = target;
  42389. return _this;
  42390. }
  42391. IncrementValueAction.prototype._prepare = function () {
  42392. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  42393. this._property = this._getProperty(this.propertyPath);
  42394. if (typeof this._effectiveTarget[this._property] !== "number") {
  42395. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  42396. }
  42397. };
  42398. IncrementValueAction.prototype.execute = function () {
  42399. this._effectiveTarget[this._property] += this.value;
  42400. if (this._target.markAsDirty) {
  42401. this._target.markAsDirty(this._property);
  42402. }
  42403. };
  42404. IncrementValueAction.prototype.serialize = function (parent) {
  42405. return _super.prototype._serialize.call(this, {
  42406. name: "IncrementValueAction",
  42407. properties: [
  42408. BABYLON.Action._GetTargetProperty(this._target),
  42409. { name: "propertyPath", value: this.propertyPath },
  42410. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  42411. ]
  42412. }, parent);
  42413. };
  42414. return IncrementValueAction;
  42415. }(BABYLON.Action));
  42416. BABYLON.IncrementValueAction = IncrementValueAction;
  42417. var PlayAnimationAction = /** @class */ (function (_super) {
  42418. __extends(PlayAnimationAction, _super);
  42419. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  42420. var _this = _super.call(this, triggerOptions, condition) || this;
  42421. _this.from = from;
  42422. _this.to = to;
  42423. _this.loop = loop;
  42424. _this._target = target;
  42425. return _this;
  42426. }
  42427. PlayAnimationAction.prototype._prepare = function () {
  42428. };
  42429. PlayAnimationAction.prototype.execute = function () {
  42430. var scene = this._actionManager.getScene();
  42431. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  42432. };
  42433. PlayAnimationAction.prototype.serialize = function (parent) {
  42434. return _super.prototype._serialize.call(this, {
  42435. name: "PlayAnimationAction",
  42436. properties: [
  42437. BABYLON.Action._GetTargetProperty(this._target),
  42438. { name: "from", value: String(this.from) },
  42439. { name: "to", value: String(this.to) },
  42440. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  42441. ]
  42442. }, parent);
  42443. };
  42444. return PlayAnimationAction;
  42445. }(BABYLON.Action));
  42446. BABYLON.PlayAnimationAction = PlayAnimationAction;
  42447. var StopAnimationAction = /** @class */ (function (_super) {
  42448. __extends(StopAnimationAction, _super);
  42449. function StopAnimationAction(triggerOptions, target, condition) {
  42450. var _this = _super.call(this, triggerOptions, condition) || this;
  42451. _this._target = target;
  42452. return _this;
  42453. }
  42454. StopAnimationAction.prototype._prepare = function () {
  42455. };
  42456. StopAnimationAction.prototype.execute = function () {
  42457. var scene = this._actionManager.getScene();
  42458. scene.stopAnimation(this._target);
  42459. };
  42460. StopAnimationAction.prototype.serialize = function (parent) {
  42461. return _super.prototype._serialize.call(this, {
  42462. name: "StopAnimationAction",
  42463. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  42464. }, parent);
  42465. };
  42466. return StopAnimationAction;
  42467. }(BABYLON.Action));
  42468. BABYLON.StopAnimationAction = StopAnimationAction;
  42469. var DoNothingAction = /** @class */ (function (_super) {
  42470. __extends(DoNothingAction, _super);
  42471. function DoNothingAction(triggerOptions, condition) {
  42472. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  42473. return _super.call(this, triggerOptions, condition) || this;
  42474. }
  42475. DoNothingAction.prototype.execute = function () {
  42476. };
  42477. DoNothingAction.prototype.serialize = function (parent) {
  42478. return _super.prototype._serialize.call(this, {
  42479. name: "DoNothingAction",
  42480. properties: []
  42481. }, parent);
  42482. };
  42483. return DoNothingAction;
  42484. }(BABYLON.Action));
  42485. BABYLON.DoNothingAction = DoNothingAction;
  42486. var CombineAction = /** @class */ (function (_super) {
  42487. __extends(CombineAction, _super);
  42488. function CombineAction(triggerOptions, children, condition) {
  42489. var _this = _super.call(this, triggerOptions, condition) || this;
  42490. _this.children = children;
  42491. return _this;
  42492. }
  42493. CombineAction.prototype._prepare = function () {
  42494. for (var index = 0; index < this.children.length; index++) {
  42495. this.children[index]._actionManager = this._actionManager;
  42496. this.children[index]._prepare();
  42497. }
  42498. };
  42499. CombineAction.prototype.execute = function (evt) {
  42500. for (var index = 0; index < this.children.length; index++) {
  42501. this.children[index].execute(evt);
  42502. }
  42503. };
  42504. CombineAction.prototype.serialize = function (parent) {
  42505. var serializationObject = _super.prototype._serialize.call(this, {
  42506. name: "CombineAction",
  42507. properties: [],
  42508. combine: []
  42509. }, parent);
  42510. for (var i = 0; i < this.children.length; i++) {
  42511. serializationObject.combine.push(this.children[i].serialize(null));
  42512. }
  42513. return serializationObject;
  42514. };
  42515. return CombineAction;
  42516. }(BABYLON.Action));
  42517. BABYLON.CombineAction = CombineAction;
  42518. var ExecuteCodeAction = /** @class */ (function (_super) {
  42519. __extends(ExecuteCodeAction, _super);
  42520. function ExecuteCodeAction(triggerOptions, func, condition) {
  42521. var _this = _super.call(this, triggerOptions, condition) || this;
  42522. _this.func = func;
  42523. return _this;
  42524. }
  42525. ExecuteCodeAction.prototype.execute = function (evt) {
  42526. this.func(evt);
  42527. };
  42528. return ExecuteCodeAction;
  42529. }(BABYLON.Action));
  42530. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  42531. var SetParentAction = /** @class */ (function (_super) {
  42532. __extends(SetParentAction, _super);
  42533. function SetParentAction(triggerOptions, target, parent, condition) {
  42534. var _this = _super.call(this, triggerOptions, condition) || this;
  42535. _this._target = target;
  42536. _this._parent = parent;
  42537. return _this;
  42538. }
  42539. SetParentAction.prototype._prepare = function () {
  42540. };
  42541. SetParentAction.prototype.execute = function () {
  42542. if (this._target.parent === this._parent) {
  42543. return;
  42544. }
  42545. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  42546. invertParentWorldMatrix.invert();
  42547. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  42548. this._target.parent = this._parent;
  42549. };
  42550. SetParentAction.prototype.serialize = function (parent) {
  42551. return _super.prototype._serialize.call(this, {
  42552. name: "SetParentAction",
  42553. properties: [
  42554. BABYLON.Action._GetTargetProperty(this._target),
  42555. BABYLON.Action._GetTargetProperty(this._parent),
  42556. ]
  42557. }, parent);
  42558. };
  42559. return SetParentAction;
  42560. }(BABYLON.Action));
  42561. BABYLON.SetParentAction = SetParentAction;
  42562. var PlaySoundAction = /** @class */ (function (_super) {
  42563. __extends(PlaySoundAction, _super);
  42564. function PlaySoundAction(triggerOptions, sound, condition) {
  42565. var _this = _super.call(this, triggerOptions, condition) || this;
  42566. _this._sound = sound;
  42567. return _this;
  42568. }
  42569. PlaySoundAction.prototype._prepare = function () {
  42570. };
  42571. PlaySoundAction.prototype.execute = function () {
  42572. if (this._sound !== undefined)
  42573. this._sound.play();
  42574. };
  42575. PlaySoundAction.prototype.serialize = function (parent) {
  42576. return _super.prototype._serialize.call(this, {
  42577. name: "PlaySoundAction",
  42578. properties: [{ name: "sound", value: this._sound.name }]
  42579. }, parent);
  42580. };
  42581. return PlaySoundAction;
  42582. }(BABYLON.Action));
  42583. BABYLON.PlaySoundAction = PlaySoundAction;
  42584. var StopSoundAction = /** @class */ (function (_super) {
  42585. __extends(StopSoundAction, _super);
  42586. function StopSoundAction(triggerOptions, sound, condition) {
  42587. var _this = _super.call(this, triggerOptions, condition) || this;
  42588. _this._sound = sound;
  42589. return _this;
  42590. }
  42591. StopSoundAction.prototype._prepare = function () {
  42592. };
  42593. StopSoundAction.prototype.execute = function () {
  42594. if (this._sound !== undefined)
  42595. this._sound.stop();
  42596. };
  42597. StopSoundAction.prototype.serialize = function (parent) {
  42598. return _super.prototype._serialize.call(this, {
  42599. name: "StopSoundAction",
  42600. properties: [{ name: "sound", value: this._sound.name }]
  42601. }, parent);
  42602. };
  42603. return StopSoundAction;
  42604. }(BABYLON.Action));
  42605. BABYLON.StopSoundAction = StopSoundAction;
  42606. })(BABYLON || (BABYLON = {}));
  42607. //# sourceMappingURL=babylon.directActions.js.map
  42608. var BABYLON;
  42609. (function (BABYLON) {
  42610. var SpriteManager = /** @class */ (function () {
  42611. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  42612. if (epsilon === void 0) { epsilon = 0.01; }
  42613. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  42614. this.name = name;
  42615. this.sprites = new Array();
  42616. this.renderingGroupId = 0;
  42617. this.layerMask = 0x0FFFFFFF;
  42618. this.fogEnabled = true;
  42619. this.isPickable = false;
  42620. /**
  42621. * An event triggered when the manager is disposed.
  42622. * @type {BABYLON.Observable}
  42623. */
  42624. this.onDisposeObservable = new BABYLON.Observable();
  42625. this._vertexBuffers = {};
  42626. this._capacity = capacity;
  42627. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  42628. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42629. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  42630. if (cellSize.width && cellSize.height) {
  42631. this.cellWidth = cellSize.width;
  42632. this.cellHeight = cellSize.height;
  42633. }
  42634. else if (cellSize !== undefined) {
  42635. this.cellWidth = cellSize;
  42636. this.cellHeight = cellSize;
  42637. }
  42638. else {
  42639. return;
  42640. }
  42641. this._epsilon = epsilon;
  42642. this._scene = scene;
  42643. this._scene.spriteManagers.push(this);
  42644. var indices = [];
  42645. var index = 0;
  42646. for (var count = 0; count < capacity; count++) {
  42647. indices.push(index);
  42648. indices.push(index + 1);
  42649. indices.push(index + 2);
  42650. indices.push(index);
  42651. indices.push(index + 2);
  42652. indices.push(index + 3);
  42653. index += 4;
  42654. }
  42655. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  42656. // VBO
  42657. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  42658. this._vertexData = new Float32Array(capacity * 16 * 4);
  42659. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  42660. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  42661. var options = this._buffer.createVertexBuffer("options", 4, 4);
  42662. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  42663. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  42664. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  42665. this._vertexBuffers["options"] = options;
  42666. this._vertexBuffers["cellInfo"] = cellInfo;
  42667. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  42668. // Effects
  42669. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  42670. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  42671. }
  42672. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  42673. set: function (callback) {
  42674. if (this._onDisposeObserver) {
  42675. this.onDisposeObservable.remove(this._onDisposeObserver);
  42676. }
  42677. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  42678. },
  42679. enumerable: true,
  42680. configurable: true
  42681. });
  42682. Object.defineProperty(SpriteManager.prototype, "texture", {
  42683. get: function () {
  42684. return this._spriteTexture;
  42685. },
  42686. set: function (value) {
  42687. this._spriteTexture = value;
  42688. },
  42689. enumerable: true,
  42690. configurable: true
  42691. });
  42692. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  42693. var arrayOffset = index * 16;
  42694. if (offsetX === 0)
  42695. offsetX = this._epsilon;
  42696. else if (offsetX === 1)
  42697. offsetX = 1 - this._epsilon;
  42698. if (offsetY === 0)
  42699. offsetY = this._epsilon;
  42700. else if (offsetY === 1)
  42701. offsetY = 1 - this._epsilon;
  42702. this._vertexData[arrayOffset] = sprite.position.x;
  42703. this._vertexData[arrayOffset + 1] = sprite.position.y;
  42704. this._vertexData[arrayOffset + 2] = sprite.position.z;
  42705. this._vertexData[arrayOffset + 3] = sprite.angle;
  42706. this._vertexData[arrayOffset + 4] = sprite.width;
  42707. this._vertexData[arrayOffset + 5] = sprite.height;
  42708. this._vertexData[arrayOffset + 6] = offsetX;
  42709. this._vertexData[arrayOffset + 7] = offsetY;
  42710. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  42711. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  42712. var offset = (sprite.cellIndex / rowSize) >> 0;
  42713. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  42714. this._vertexData[arrayOffset + 11] = offset;
  42715. // Color
  42716. this._vertexData[arrayOffset + 12] = sprite.color.r;
  42717. this._vertexData[arrayOffset + 13] = sprite.color.g;
  42718. this._vertexData[arrayOffset + 14] = sprite.color.b;
  42719. this._vertexData[arrayOffset + 15] = sprite.color.a;
  42720. };
  42721. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  42722. var count = Math.min(this._capacity, this.sprites.length);
  42723. var min = BABYLON.Vector3.Zero();
  42724. var max = BABYLON.Vector3.Zero();
  42725. var distance = Number.MAX_VALUE;
  42726. var currentSprite = null;
  42727. var cameraSpacePosition = BABYLON.Vector3.Zero();
  42728. var cameraView = camera.getViewMatrix();
  42729. for (var index = 0; index < count; index++) {
  42730. var sprite = this.sprites[index];
  42731. if (!sprite) {
  42732. continue;
  42733. }
  42734. if (predicate) {
  42735. if (!predicate(sprite)) {
  42736. continue;
  42737. }
  42738. }
  42739. else if (!sprite.isPickable) {
  42740. continue;
  42741. }
  42742. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  42743. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  42744. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  42745. if (ray.intersectsBoxMinMax(min, max)) {
  42746. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  42747. if (distance > currentDistance) {
  42748. distance = currentDistance;
  42749. currentSprite = sprite;
  42750. if (fastCheck) {
  42751. break;
  42752. }
  42753. }
  42754. }
  42755. }
  42756. if (currentSprite) {
  42757. var result = new BABYLON.PickingInfo();
  42758. result.hit = true;
  42759. result.pickedSprite = currentSprite;
  42760. result.distance = distance;
  42761. return result;
  42762. }
  42763. return null;
  42764. };
  42765. SpriteManager.prototype.render = function () {
  42766. // Check
  42767. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  42768. return;
  42769. var engine = this._scene.getEngine();
  42770. var baseSize = this._spriteTexture.getBaseSize();
  42771. // Sprites
  42772. var deltaTime = engine.getDeltaTime();
  42773. var max = Math.min(this._capacity, this.sprites.length);
  42774. var rowSize = baseSize.width / this.cellWidth;
  42775. var offset = 0;
  42776. for (var index = 0; index < max; index++) {
  42777. var sprite = this.sprites[index];
  42778. if (!sprite) {
  42779. continue;
  42780. }
  42781. sprite._animate(deltaTime);
  42782. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  42783. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  42784. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  42785. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  42786. }
  42787. this._buffer.update(this._vertexData);
  42788. // Render
  42789. var effect = this._effectBase;
  42790. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42791. effect = this._effectFog;
  42792. }
  42793. engine.enableEffect(effect);
  42794. var viewMatrix = this._scene.getViewMatrix();
  42795. effect.setTexture("diffuseSampler", this._spriteTexture);
  42796. effect.setMatrix("view", viewMatrix);
  42797. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  42798. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  42799. // Fog
  42800. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  42801. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  42802. effect.setColor3("vFogColor", this._scene.fogColor);
  42803. }
  42804. // VBOs
  42805. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  42806. // Draw order
  42807. engine.setDepthFunctionToLessOrEqual();
  42808. effect.setBool("alphaTest", true);
  42809. engine.setColorWrite(false);
  42810. engine.draw(true, 0, max * 6);
  42811. engine.setColorWrite(true);
  42812. effect.setBool("alphaTest", false);
  42813. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  42814. engine.draw(true, 0, max * 6);
  42815. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  42816. };
  42817. SpriteManager.prototype.dispose = function () {
  42818. if (this._buffer) {
  42819. this._buffer.dispose();
  42820. this._buffer = null;
  42821. }
  42822. if (this._indexBuffer) {
  42823. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  42824. this._indexBuffer = null;
  42825. }
  42826. if (this._spriteTexture) {
  42827. this._spriteTexture.dispose();
  42828. this._spriteTexture = null;
  42829. }
  42830. // Remove from scene
  42831. var index = this._scene.spriteManagers.indexOf(this);
  42832. this._scene.spriteManagers.splice(index, 1);
  42833. // Callback
  42834. this.onDisposeObservable.notifyObservers(this);
  42835. this.onDisposeObservable.clear();
  42836. };
  42837. return SpriteManager;
  42838. }());
  42839. BABYLON.SpriteManager = SpriteManager;
  42840. })(BABYLON || (BABYLON = {}));
  42841. //# sourceMappingURL=babylon.spriteManager.js.map
  42842. var BABYLON;
  42843. (function (BABYLON) {
  42844. var Sprite = /** @class */ (function () {
  42845. function Sprite(name, manager) {
  42846. this.name = name;
  42847. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  42848. this.width = 1.0;
  42849. this.height = 1.0;
  42850. this.angle = 0;
  42851. this.cellIndex = 0;
  42852. this.invertU = 0;
  42853. this.invertV = 0;
  42854. this.animations = new Array();
  42855. this.isPickable = false;
  42856. this._animationStarted = false;
  42857. this._loopAnimation = false;
  42858. this._fromIndex = 0;
  42859. this._toIndex = 0;
  42860. this._delay = 0;
  42861. this._direction = 1;
  42862. this._time = 0;
  42863. this._manager = manager;
  42864. this._manager.sprites.push(this);
  42865. this.position = BABYLON.Vector3.Zero();
  42866. }
  42867. Object.defineProperty(Sprite.prototype, "size", {
  42868. get: function () {
  42869. return this.width;
  42870. },
  42871. set: function (value) {
  42872. this.width = value;
  42873. this.height = value;
  42874. },
  42875. enumerable: true,
  42876. configurable: true
  42877. });
  42878. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  42879. this._fromIndex = from;
  42880. this._toIndex = to;
  42881. this._loopAnimation = loop;
  42882. this._delay = delay;
  42883. this._animationStarted = true;
  42884. this._direction = from < to ? 1 : -1;
  42885. this.cellIndex = from;
  42886. this._time = 0;
  42887. this._onAnimationEnd = onAnimationEnd;
  42888. };
  42889. Sprite.prototype.stopAnimation = function () {
  42890. this._animationStarted = false;
  42891. };
  42892. Sprite.prototype._animate = function (deltaTime) {
  42893. if (!this._animationStarted)
  42894. return;
  42895. this._time += deltaTime;
  42896. if (this._time > this._delay) {
  42897. this._time = this._time % this._delay;
  42898. this.cellIndex += this._direction;
  42899. if (this.cellIndex > this._toIndex) {
  42900. if (this._loopAnimation) {
  42901. this.cellIndex = this._fromIndex;
  42902. }
  42903. else {
  42904. this.cellIndex = this._toIndex;
  42905. this._animationStarted = false;
  42906. if (this._onAnimationEnd) {
  42907. this._onAnimationEnd();
  42908. }
  42909. if (this.disposeWhenFinishedAnimating) {
  42910. this.dispose();
  42911. }
  42912. }
  42913. }
  42914. }
  42915. };
  42916. Sprite.prototype.dispose = function () {
  42917. for (var i = 0; i < this._manager.sprites.length; i++) {
  42918. if (this._manager.sprites[i] == this) {
  42919. this._manager.sprites.splice(i, 1);
  42920. }
  42921. }
  42922. };
  42923. return Sprite;
  42924. }());
  42925. BABYLON.Sprite = Sprite;
  42926. })(BABYLON || (BABYLON = {}));
  42927. //# sourceMappingURL=babylon.sprite.js.map
  42928. var BABYLON;
  42929. (function (BABYLON) {
  42930. var IntersectionInfo = /** @class */ (function () {
  42931. function IntersectionInfo(bu, bv, distance) {
  42932. this.bu = bu;
  42933. this.bv = bv;
  42934. this.distance = distance;
  42935. this.faceId = 0;
  42936. this.subMeshId = 0;
  42937. }
  42938. return IntersectionInfo;
  42939. }());
  42940. BABYLON.IntersectionInfo = IntersectionInfo;
  42941. var PickingInfo = /** @class */ (function () {
  42942. function PickingInfo() {
  42943. this.hit = false;
  42944. this.distance = 0;
  42945. this.pickedPoint = null;
  42946. this.pickedMesh = null;
  42947. this.bu = 0;
  42948. this.bv = 0;
  42949. this.faceId = -1;
  42950. this.subMeshId = 0;
  42951. this.pickedSprite = null;
  42952. }
  42953. // Methods
  42954. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  42955. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  42956. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  42957. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  42958. return null;
  42959. }
  42960. var indices = this.pickedMesh.getIndices();
  42961. if (!indices) {
  42962. return null;
  42963. }
  42964. var result;
  42965. if (useVerticesNormals) {
  42966. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42967. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  42968. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  42969. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  42970. normal0 = normal0.scale(this.bu);
  42971. normal1 = normal1.scale(this.bv);
  42972. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  42973. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  42974. }
  42975. else {
  42976. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42977. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  42978. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  42979. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  42980. var p1p2 = vertex1.subtract(vertex2);
  42981. var p3p2 = vertex3.subtract(vertex2);
  42982. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  42983. }
  42984. if (useWorldCoordinates) {
  42985. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  42986. }
  42987. return BABYLON.Vector3.Normalize(result);
  42988. };
  42989. PickingInfo.prototype.getTextureCoordinates = function () {
  42990. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42991. return null;
  42992. }
  42993. var indices = this.pickedMesh.getIndices();
  42994. if (!indices) {
  42995. return null;
  42996. }
  42997. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42998. if (!uvs) {
  42999. return null;
  43000. }
  43001. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  43002. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  43003. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  43004. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  43005. uv1 = uv1.scale(this.bu);
  43006. uv2 = uv2.scale(this.bv);
  43007. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  43008. };
  43009. return PickingInfo;
  43010. }());
  43011. BABYLON.PickingInfo = PickingInfo;
  43012. })(BABYLON || (BABYLON = {}));
  43013. //# sourceMappingURL=babylon.pickingInfo.js.map
  43014. var BABYLON;
  43015. (function (BABYLON) {
  43016. var Ray = /** @class */ (function () {
  43017. function Ray(origin, direction, length) {
  43018. if (length === void 0) { length = Number.MAX_VALUE; }
  43019. this.origin = origin;
  43020. this.direction = direction;
  43021. this.length = length;
  43022. }
  43023. // Methods
  43024. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  43025. var d = 0.0;
  43026. var maxValue = Number.MAX_VALUE;
  43027. var inv;
  43028. var min;
  43029. var max;
  43030. var temp;
  43031. if (Math.abs(this.direction.x) < 0.0000001) {
  43032. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  43033. return false;
  43034. }
  43035. }
  43036. else {
  43037. inv = 1.0 / this.direction.x;
  43038. min = (minimum.x - this.origin.x) * inv;
  43039. max = (maximum.x - this.origin.x) * inv;
  43040. if (max === -Infinity) {
  43041. max = Infinity;
  43042. }
  43043. if (min > max) {
  43044. temp = min;
  43045. min = max;
  43046. max = temp;
  43047. }
  43048. d = Math.max(min, d);
  43049. maxValue = Math.min(max, maxValue);
  43050. if (d > maxValue) {
  43051. return false;
  43052. }
  43053. }
  43054. if (Math.abs(this.direction.y) < 0.0000001) {
  43055. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  43056. return false;
  43057. }
  43058. }
  43059. else {
  43060. inv = 1.0 / this.direction.y;
  43061. min = (minimum.y - this.origin.y) * inv;
  43062. max = (maximum.y - this.origin.y) * inv;
  43063. if (max === -Infinity) {
  43064. max = Infinity;
  43065. }
  43066. if (min > max) {
  43067. temp = min;
  43068. min = max;
  43069. max = temp;
  43070. }
  43071. d = Math.max(min, d);
  43072. maxValue = Math.min(max, maxValue);
  43073. if (d > maxValue) {
  43074. return false;
  43075. }
  43076. }
  43077. if (Math.abs(this.direction.z) < 0.0000001) {
  43078. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  43079. return false;
  43080. }
  43081. }
  43082. else {
  43083. inv = 1.0 / this.direction.z;
  43084. min = (minimum.z - this.origin.z) * inv;
  43085. max = (maximum.z - this.origin.z) * inv;
  43086. if (max === -Infinity) {
  43087. max = Infinity;
  43088. }
  43089. if (min > max) {
  43090. temp = min;
  43091. min = max;
  43092. max = temp;
  43093. }
  43094. d = Math.max(min, d);
  43095. maxValue = Math.min(max, maxValue);
  43096. if (d > maxValue) {
  43097. return false;
  43098. }
  43099. }
  43100. return true;
  43101. };
  43102. Ray.prototype.intersectsBox = function (box) {
  43103. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  43104. };
  43105. Ray.prototype.intersectsSphere = function (sphere) {
  43106. var x = sphere.center.x - this.origin.x;
  43107. var y = sphere.center.y - this.origin.y;
  43108. var z = sphere.center.z - this.origin.z;
  43109. var pyth = (x * x) + (y * y) + (z * z);
  43110. var rr = sphere.radius * sphere.radius;
  43111. if (pyth <= rr) {
  43112. return true;
  43113. }
  43114. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  43115. if (dot < 0.0) {
  43116. return false;
  43117. }
  43118. var temp = pyth - (dot * dot);
  43119. return temp <= rr;
  43120. };
  43121. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  43122. if (!this._edge1) {
  43123. this._edge1 = BABYLON.Vector3.Zero();
  43124. this._edge2 = BABYLON.Vector3.Zero();
  43125. this._pvec = BABYLON.Vector3.Zero();
  43126. this._tvec = BABYLON.Vector3.Zero();
  43127. this._qvec = BABYLON.Vector3.Zero();
  43128. }
  43129. vertex1.subtractToRef(vertex0, this._edge1);
  43130. vertex2.subtractToRef(vertex0, this._edge2);
  43131. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  43132. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  43133. if (det === 0) {
  43134. return null;
  43135. }
  43136. var invdet = 1 / det;
  43137. this.origin.subtractToRef(vertex0, this._tvec);
  43138. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  43139. if (bu < 0 || bu > 1.0) {
  43140. return null;
  43141. }
  43142. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  43143. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  43144. if (bv < 0 || bu + bv > 1.0) {
  43145. return null;
  43146. }
  43147. //check if the distance is longer than the predefined length.
  43148. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  43149. if (distance > this.length) {
  43150. return null;
  43151. }
  43152. return new BABYLON.IntersectionInfo(bu, bv, distance);
  43153. };
  43154. Ray.prototype.intersectsPlane = function (plane) {
  43155. var distance;
  43156. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  43157. if (Math.abs(result1) < 9.99999997475243E-07) {
  43158. return null;
  43159. }
  43160. else {
  43161. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  43162. distance = (-plane.d - result2) / result1;
  43163. if (distance < 0.0) {
  43164. if (distance < -9.99999997475243E-07) {
  43165. return null;
  43166. }
  43167. else {
  43168. return 0;
  43169. }
  43170. }
  43171. return distance;
  43172. }
  43173. };
  43174. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  43175. var tm = BABYLON.Tmp.Matrix[0];
  43176. mesh.getWorldMatrix().invertToRef(tm);
  43177. if (this._tmpRay) {
  43178. Ray.TransformToRef(this, tm, this._tmpRay);
  43179. }
  43180. else {
  43181. this._tmpRay = Ray.Transform(this, tm);
  43182. }
  43183. return mesh.intersects(this._tmpRay, fastCheck);
  43184. };
  43185. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  43186. if (results) {
  43187. results.length = 0;
  43188. }
  43189. else {
  43190. results = [];
  43191. }
  43192. for (var i = 0; i < meshes.length; i++) {
  43193. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  43194. if (pickInfo.hit) {
  43195. results.push(pickInfo);
  43196. }
  43197. }
  43198. results.sort(this._comparePickingInfo);
  43199. return results;
  43200. };
  43201. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  43202. if (pickingInfoA.distance < pickingInfoB.distance) {
  43203. return -1;
  43204. }
  43205. else if (pickingInfoA.distance > pickingInfoB.distance) {
  43206. return 1;
  43207. }
  43208. else {
  43209. return 0;
  43210. }
  43211. };
  43212. /**
  43213. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  43214. * @param sega the first point of the segment to test the intersection against
  43215. * @param segb the second point of the segment to test the intersection against
  43216. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  43217. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  43218. */
  43219. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  43220. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  43221. var u = segb.subtract(sega);
  43222. var v = rsegb.subtract(this.origin);
  43223. var w = sega.subtract(this.origin);
  43224. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  43225. var b = BABYLON.Vector3.Dot(u, v);
  43226. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  43227. var d = BABYLON.Vector3.Dot(u, w);
  43228. var e = BABYLON.Vector3.Dot(v, w);
  43229. var D = a * c - b * b; // always >= 0
  43230. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  43231. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  43232. // compute the line parameters of the two closest points
  43233. if (D < Ray.smallnum) {
  43234. sN = 0.0; // force using point P0 on segment S1
  43235. sD = 1.0; // to prevent possible division by 0.0 later
  43236. tN = e;
  43237. tD = c;
  43238. }
  43239. else {
  43240. sN = (b * e - c * d);
  43241. tN = (a * e - b * d);
  43242. if (sN < 0.0) {
  43243. sN = 0.0;
  43244. tN = e;
  43245. tD = c;
  43246. }
  43247. else if (sN > sD) {
  43248. sN = sD;
  43249. tN = e + b;
  43250. tD = c;
  43251. }
  43252. }
  43253. if (tN < 0.0) {
  43254. tN = 0.0;
  43255. // recompute sc for this edge
  43256. if (-d < 0.0) {
  43257. sN = 0.0;
  43258. }
  43259. else if (-d > a)
  43260. sN = sD;
  43261. else {
  43262. sN = -d;
  43263. sD = a;
  43264. }
  43265. }
  43266. else if (tN > tD) {
  43267. tN = tD;
  43268. // recompute sc for this edge
  43269. if ((-d + b) < 0.0) {
  43270. sN = 0;
  43271. }
  43272. else if ((-d + b) > a) {
  43273. sN = sD;
  43274. }
  43275. else {
  43276. sN = (-d + b);
  43277. sD = a;
  43278. }
  43279. }
  43280. // finally do the division to get sc and tc
  43281. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  43282. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  43283. // get the difference of the two closest points
  43284. var qtc = v.multiplyByFloats(tc, tc, tc);
  43285. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  43286. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  43287. if (isIntersected) {
  43288. return qtc.length();
  43289. }
  43290. return -1;
  43291. };
  43292. // Statics
  43293. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  43294. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  43295. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  43296. var direction = end.subtract(start);
  43297. direction.normalize();
  43298. return new Ray(start, direction);
  43299. };
  43300. /**
  43301. * 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
  43302. * transformed to the given world matrix.
  43303. * @param origin The origin point
  43304. * @param end The end point
  43305. * @param world a matrix to transform the ray to. Default is the identity matrix.
  43306. */
  43307. Ray.CreateNewFromTo = function (origin, end, world) {
  43308. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  43309. var direction = end.subtract(origin);
  43310. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  43311. direction.normalize();
  43312. return Ray.Transform(new Ray(origin, direction, length), world);
  43313. };
  43314. Ray.Transform = function (ray, matrix) {
  43315. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  43316. Ray.TransformToRef(ray, matrix, result);
  43317. return result;
  43318. };
  43319. Ray.TransformToRef = function (ray, matrix, result) {
  43320. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  43321. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  43322. result.length = ray.length;
  43323. var dir = result.direction;
  43324. var len = dir.length();
  43325. if (!(len === 0 || len === 1)) {
  43326. var num = 1.0 / len;
  43327. dir.x *= num;
  43328. dir.y *= num;
  43329. dir.z *= num;
  43330. result.length *= len;
  43331. }
  43332. };
  43333. Ray.smallnum = 0.00000001;
  43334. Ray.rayl = 10e8;
  43335. return Ray;
  43336. }());
  43337. BABYLON.Ray = Ray;
  43338. })(BABYLON || (BABYLON = {}));
  43339. //# sourceMappingURL=babylon.ray.js.map
  43340. var BABYLON;
  43341. (function (BABYLON) {
  43342. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  43343. if (boxMin.x > sphereCenter.x + sphereRadius)
  43344. return false;
  43345. if (sphereCenter.x - sphereRadius > boxMax.x)
  43346. return false;
  43347. if (boxMin.y > sphereCenter.y + sphereRadius)
  43348. return false;
  43349. if (sphereCenter.y - sphereRadius > boxMax.y)
  43350. return false;
  43351. if (boxMin.z > sphereCenter.z + sphereRadius)
  43352. return false;
  43353. if (sphereCenter.z - sphereRadius > boxMax.z)
  43354. return false;
  43355. return true;
  43356. };
  43357. var getLowestRoot = (function () {
  43358. var result = { root: 0, found: false };
  43359. return function (a, b, c, maxR) {
  43360. result.root = 0;
  43361. result.found = false;
  43362. var determinant = b * b - 4.0 * a * c;
  43363. if (determinant < 0)
  43364. return result;
  43365. var sqrtD = Math.sqrt(determinant);
  43366. var r1 = (-b - sqrtD) / (2.0 * a);
  43367. var r2 = (-b + sqrtD) / (2.0 * a);
  43368. if (r1 > r2) {
  43369. var temp = r2;
  43370. r2 = r1;
  43371. r1 = temp;
  43372. }
  43373. if (r1 > 0 && r1 < maxR) {
  43374. result.root = r1;
  43375. result.found = true;
  43376. return result;
  43377. }
  43378. if (r2 > 0 && r2 < maxR) {
  43379. result.root = r2;
  43380. result.found = true;
  43381. return result;
  43382. }
  43383. return result;
  43384. };
  43385. })();
  43386. var Collider = /** @class */ (function () {
  43387. function Collider() {
  43388. this.radius = BABYLON.Vector3.One();
  43389. this.retry = 0;
  43390. this.basePointWorld = BABYLON.Vector3.Zero();
  43391. this.velocityWorld = BABYLON.Vector3.Zero();
  43392. this.normalizedVelocity = BABYLON.Vector3.Zero();
  43393. this._collisionPoint = BABYLON.Vector3.Zero();
  43394. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  43395. this._tempVector = BABYLON.Vector3.Zero();
  43396. this._tempVector2 = BABYLON.Vector3.Zero();
  43397. this._tempVector3 = BABYLON.Vector3.Zero();
  43398. this._tempVector4 = BABYLON.Vector3.Zero();
  43399. this._edge = BABYLON.Vector3.Zero();
  43400. this._baseToVertex = BABYLON.Vector3.Zero();
  43401. this._destinationPoint = BABYLON.Vector3.Zero();
  43402. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  43403. this._displacementVector = BABYLON.Vector3.Zero();
  43404. this._collisionMask = -1;
  43405. }
  43406. Object.defineProperty(Collider.prototype, "collisionMask", {
  43407. get: function () {
  43408. return this._collisionMask;
  43409. },
  43410. set: function (mask) {
  43411. this._collisionMask = !isNaN(mask) ? mask : -1;
  43412. },
  43413. enumerable: true,
  43414. configurable: true
  43415. });
  43416. // Methods
  43417. Collider.prototype._initialize = function (source, dir, e) {
  43418. this.velocity = dir;
  43419. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  43420. this.basePoint = source;
  43421. source.multiplyToRef(this.radius, this.basePointWorld);
  43422. dir.multiplyToRef(this.radius, this.velocityWorld);
  43423. this.velocityWorldLength = this.velocityWorld.length();
  43424. this.epsilon = e;
  43425. this.collisionFound = false;
  43426. };
  43427. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  43428. pa.subtractToRef(point, this._tempVector);
  43429. pb.subtractToRef(point, this._tempVector2);
  43430. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  43431. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43432. if (d < 0)
  43433. return false;
  43434. pc.subtractToRef(point, this._tempVector3);
  43435. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  43436. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43437. if (d < 0)
  43438. return false;
  43439. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  43440. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  43441. return d >= 0;
  43442. };
  43443. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  43444. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  43445. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  43446. if (distance > this.velocityWorldLength + max + sphereRadius) {
  43447. return false;
  43448. }
  43449. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  43450. return false;
  43451. return true;
  43452. };
  43453. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  43454. var t0;
  43455. var embeddedInPlane = false;
  43456. //defensive programming, actually not needed.
  43457. if (!trianglePlaneArray) {
  43458. trianglePlaneArray = [];
  43459. }
  43460. if (!trianglePlaneArray[faceIndex]) {
  43461. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  43462. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  43463. }
  43464. var trianglePlane = trianglePlaneArray[faceIndex];
  43465. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  43466. return;
  43467. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  43468. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  43469. if (normalDotVelocity == 0) {
  43470. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  43471. return;
  43472. embeddedInPlane = true;
  43473. t0 = 0;
  43474. }
  43475. else {
  43476. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43477. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  43478. if (t0 > t1) {
  43479. var temp = t1;
  43480. t1 = t0;
  43481. t0 = temp;
  43482. }
  43483. if (t0 > 1.0 || t1 < 0.0)
  43484. return;
  43485. if (t0 < 0)
  43486. t0 = 0;
  43487. if (t0 > 1.0)
  43488. t0 = 1.0;
  43489. }
  43490. this._collisionPoint.copyFromFloats(0, 0, 0);
  43491. var found = false;
  43492. var t = 1.0;
  43493. if (!embeddedInPlane) {
  43494. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  43495. this.velocity.scaleToRef(t0, this._tempVector);
  43496. this._planeIntersectionPoint.addInPlace(this._tempVector);
  43497. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  43498. found = true;
  43499. t = t0;
  43500. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  43501. }
  43502. }
  43503. if (!found) {
  43504. var velocitySquaredLength = this.velocity.lengthSquared();
  43505. var a = velocitySquaredLength;
  43506. this.basePoint.subtractToRef(p1, this._tempVector);
  43507. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43508. var c = this._tempVector.lengthSquared() - 1.0;
  43509. var lowestRoot = getLowestRoot(a, b, c, t);
  43510. if (lowestRoot.found) {
  43511. t = lowestRoot.root;
  43512. found = true;
  43513. this._collisionPoint.copyFrom(p1);
  43514. }
  43515. this.basePoint.subtractToRef(p2, this._tempVector);
  43516. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43517. c = this._tempVector.lengthSquared() - 1.0;
  43518. lowestRoot = getLowestRoot(a, b, c, t);
  43519. if (lowestRoot.found) {
  43520. t = lowestRoot.root;
  43521. found = true;
  43522. this._collisionPoint.copyFrom(p2);
  43523. }
  43524. this.basePoint.subtractToRef(p3, this._tempVector);
  43525. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  43526. c = this._tempVector.lengthSquared() - 1.0;
  43527. lowestRoot = getLowestRoot(a, b, c, t);
  43528. if (lowestRoot.found) {
  43529. t = lowestRoot.root;
  43530. found = true;
  43531. this._collisionPoint.copyFrom(p3);
  43532. }
  43533. p2.subtractToRef(p1, this._edge);
  43534. p1.subtractToRef(this.basePoint, this._baseToVertex);
  43535. var edgeSquaredLength = this._edge.lengthSquared();
  43536. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43537. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43538. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43539. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43540. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43541. lowestRoot = getLowestRoot(a, b, c, t);
  43542. if (lowestRoot.found) {
  43543. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43544. if (f >= 0.0 && f <= 1.0) {
  43545. t = lowestRoot.root;
  43546. found = true;
  43547. this._edge.scaleInPlace(f);
  43548. p1.addToRef(this._edge, this._collisionPoint);
  43549. }
  43550. }
  43551. p3.subtractToRef(p2, this._edge);
  43552. p2.subtractToRef(this.basePoint, this._baseToVertex);
  43553. edgeSquaredLength = this._edge.lengthSquared();
  43554. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43555. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43556. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43557. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43558. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43559. lowestRoot = getLowestRoot(a, b, c, t);
  43560. if (lowestRoot.found) {
  43561. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43562. if (f >= 0.0 && f <= 1.0) {
  43563. t = lowestRoot.root;
  43564. found = true;
  43565. this._edge.scaleInPlace(f);
  43566. p2.addToRef(this._edge, this._collisionPoint);
  43567. }
  43568. }
  43569. p1.subtractToRef(p3, this._edge);
  43570. p3.subtractToRef(this.basePoint, this._baseToVertex);
  43571. edgeSquaredLength = this._edge.lengthSquared();
  43572. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  43573. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  43574. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  43575. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  43576. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  43577. lowestRoot = getLowestRoot(a, b, c, t);
  43578. if (lowestRoot.found) {
  43579. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  43580. if (f >= 0.0 && f <= 1.0) {
  43581. t = lowestRoot.root;
  43582. found = true;
  43583. this._edge.scaleInPlace(f);
  43584. p3.addToRef(this._edge, this._collisionPoint);
  43585. }
  43586. }
  43587. }
  43588. if (found) {
  43589. var distToCollision = t * this.velocity.length();
  43590. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  43591. if (!this.intersectionPoint) {
  43592. this.intersectionPoint = this._collisionPoint.clone();
  43593. }
  43594. else {
  43595. this.intersectionPoint.copyFrom(this._collisionPoint);
  43596. }
  43597. this.nearestDistance = distToCollision;
  43598. this.collisionFound = true;
  43599. }
  43600. }
  43601. };
  43602. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  43603. for (var i = indexStart; i < indexEnd; i += 3) {
  43604. var p1 = pts[indices[i] - decal];
  43605. var p2 = pts[indices[i + 1] - decal];
  43606. var p3 = pts[indices[i + 2] - decal];
  43607. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  43608. }
  43609. };
  43610. Collider.prototype._getResponse = function (pos, vel) {
  43611. pos.addToRef(vel, this._destinationPoint);
  43612. vel.scaleInPlace((this.nearestDistance / vel.length()));
  43613. this.basePoint.addToRef(vel, pos);
  43614. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  43615. this._slidePlaneNormal.normalize();
  43616. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  43617. pos.addInPlace(this._displacementVector);
  43618. this.intersectionPoint.addInPlace(this._displacementVector);
  43619. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  43620. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  43621. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  43622. };
  43623. return Collider;
  43624. }());
  43625. BABYLON.Collider = Collider;
  43626. })(BABYLON || (BABYLON = {}));
  43627. //# sourceMappingURL=babylon.collider.js.map
  43628. var BABYLON;
  43629. (function (BABYLON) {
  43630. //WebWorker code will be inserted to this variable.
  43631. BABYLON.CollisionWorker = "";
  43632. var WorkerTaskType;
  43633. (function (WorkerTaskType) {
  43634. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  43635. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  43636. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  43637. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  43638. var WorkerReplyType;
  43639. (function (WorkerReplyType) {
  43640. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  43641. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  43642. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  43643. var CollisionCoordinatorWorker = /** @class */ (function () {
  43644. function CollisionCoordinatorWorker() {
  43645. var _this = this;
  43646. this._scaledPosition = BABYLON.Vector3.Zero();
  43647. this._scaledVelocity = BABYLON.Vector3.Zero();
  43648. this.onMeshUpdated = function (mesh) {
  43649. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  43650. };
  43651. this.onGeometryUpdated = function (geometry) {
  43652. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  43653. };
  43654. this._afterRender = function () {
  43655. if (!_this._init)
  43656. return;
  43657. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  43658. return;
  43659. }
  43660. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  43661. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  43662. if (_this._runningUpdated > 4) {
  43663. return;
  43664. }
  43665. ++_this._runningUpdated;
  43666. var payload = {
  43667. updatedMeshes: _this._addUpdateMeshesList,
  43668. updatedGeometries: _this._addUpdateGeometriesList,
  43669. removedGeometries: _this._toRemoveGeometryArray,
  43670. removedMeshes: _this._toRemoveMeshesArray
  43671. };
  43672. var message = {
  43673. payload: payload,
  43674. taskType: WorkerTaskType.UPDATE
  43675. };
  43676. var serializable = [];
  43677. for (var id in payload.updatedGeometries) {
  43678. if (payload.updatedGeometries.hasOwnProperty(id)) {
  43679. //prepare transferables
  43680. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  43681. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  43682. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  43683. }
  43684. }
  43685. _this._worker.postMessage(message, serializable);
  43686. _this._addUpdateMeshesList = {};
  43687. _this._addUpdateGeometriesList = {};
  43688. _this._toRemoveGeometryArray = [];
  43689. _this._toRemoveMeshesArray = [];
  43690. };
  43691. this._onMessageFromWorker = function (e) {
  43692. var returnData = e.data;
  43693. if (returnData.error != WorkerReplyType.SUCCESS) {
  43694. //TODO what errors can be returned from the worker?
  43695. BABYLON.Tools.Warn("error returned from worker!");
  43696. return;
  43697. }
  43698. switch (returnData.taskType) {
  43699. case WorkerTaskType.INIT:
  43700. _this._init = true;
  43701. //Update the worked with ALL of the scene's current state
  43702. _this._scene.meshes.forEach(function (mesh) {
  43703. _this.onMeshAdded(mesh);
  43704. });
  43705. _this._scene.getGeometries().forEach(function (geometry) {
  43706. _this.onGeometryAdded(geometry);
  43707. });
  43708. break;
  43709. case WorkerTaskType.UPDATE:
  43710. _this._runningUpdated--;
  43711. break;
  43712. case WorkerTaskType.COLLIDE:
  43713. _this._runningCollisionTask = false;
  43714. var returnPayload = returnData.payload;
  43715. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  43716. return;
  43717. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  43718. if (callback) {
  43719. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  43720. if (mesh) {
  43721. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  43722. }
  43723. }
  43724. //cleanup
  43725. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  43726. break;
  43727. }
  43728. };
  43729. this._collisionsCallbackArray = [];
  43730. this._init = false;
  43731. this._runningUpdated = 0;
  43732. this._runningCollisionTask = false;
  43733. this._addUpdateMeshesList = {};
  43734. this._addUpdateGeometriesList = {};
  43735. this._toRemoveGeometryArray = [];
  43736. this._toRemoveMeshesArray = [];
  43737. }
  43738. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43739. if (!this._init)
  43740. return;
  43741. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  43742. return;
  43743. position.divideToRef(collider.radius, this._scaledPosition);
  43744. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43745. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  43746. var payload = {
  43747. collider: {
  43748. position: this._scaledPosition.asArray(),
  43749. velocity: this._scaledVelocity.asArray(),
  43750. radius: collider.radius.asArray()
  43751. },
  43752. collisionId: collisionIndex,
  43753. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  43754. maximumRetry: maximumRetry
  43755. };
  43756. var message = {
  43757. payload: payload,
  43758. taskType: WorkerTaskType.COLLIDE
  43759. };
  43760. this._worker.postMessage(message);
  43761. };
  43762. CollisionCoordinatorWorker.prototype.init = function (scene) {
  43763. this._scene = scene;
  43764. this._scene.registerAfterRender(this._afterRender);
  43765. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  43766. this._worker = new Worker(workerUrl);
  43767. this._worker.onmessage = this._onMessageFromWorker;
  43768. var message = {
  43769. payload: {},
  43770. taskType: WorkerTaskType.INIT
  43771. };
  43772. this._worker.postMessage(message);
  43773. };
  43774. CollisionCoordinatorWorker.prototype.destroy = function () {
  43775. this._scene.unregisterAfterRender(this._afterRender);
  43776. this._worker.terminate();
  43777. };
  43778. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  43779. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  43780. this.onMeshUpdated(mesh);
  43781. };
  43782. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  43783. this._toRemoveMeshesArray.push(mesh.uniqueId);
  43784. };
  43785. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  43786. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  43787. geometry.onGeometryUpdated = this.onGeometryUpdated;
  43788. this.onGeometryUpdated(geometry);
  43789. };
  43790. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  43791. this._toRemoveGeometryArray.push(geometry.id);
  43792. };
  43793. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  43794. var submeshes = [];
  43795. if (mesh.subMeshes) {
  43796. submeshes = mesh.subMeshes.map(function (sm, idx) {
  43797. var boundingInfo = sm.getBoundingInfo();
  43798. return {
  43799. position: idx,
  43800. verticesStart: sm.verticesStart,
  43801. verticesCount: sm.verticesCount,
  43802. indexStart: sm.indexStart,
  43803. indexCount: sm.indexCount,
  43804. hasMaterial: !!sm.getMaterial(),
  43805. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43806. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43807. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43808. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  43809. };
  43810. });
  43811. }
  43812. var geometryId = null;
  43813. if (mesh instanceof BABYLON.Mesh) {
  43814. var geometry = mesh.geometry;
  43815. geometryId = geometry ? geometry.id : null;
  43816. }
  43817. else if (mesh instanceof BABYLON.InstancedMesh) {
  43818. var geometry = mesh.sourceMesh.geometry;
  43819. geometryId = geometry ? geometry.id : null;
  43820. }
  43821. var boundingInfo = mesh.getBoundingInfo();
  43822. return {
  43823. uniqueId: mesh.uniqueId,
  43824. id: mesh.id,
  43825. name: mesh.name,
  43826. geometryId: geometryId,
  43827. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  43828. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  43829. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  43830. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  43831. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  43832. subMeshes: submeshes,
  43833. checkCollisions: mesh.checkCollisions
  43834. };
  43835. };
  43836. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  43837. return {
  43838. id: geometry.id,
  43839. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  43840. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  43841. indices: new Uint32Array(geometry.getIndices() || []),
  43842. };
  43843. };
  43844. return CollisionCoordinatorWorker;
  43845. }());
  43846. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  43847. var CollisionCoordinatorLegacy = /** @class */ (function () {
  43848. function CollisionCoordinatorLegacy() {
  43849. this._scaledPosition = BABYLON.Vector3.Zero();
  43850. this._scaledVelocity = BABYLON.Vector3.Zero();
  43851. this._finalPosition = BABYLON.Vector3.Zero();
  43852. }
  43853. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  43854. position.divideToRef(collider.radius, this._scaledPosition);
  43855. displacement.divideToRef(collider.radius, this._scaledVelocity);
  43856. collider.collidedMesh = null;
  43857. collider.retry = 0;
  43858. collider.initialVelocity = this._scaledVelocity;
  43859. collider.initialPosition = this._scaledPosition;
  43860. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  43861. this._finalPosition.multiplyInPlace(collider.radius);
  43862. //run the callback
  43863. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  43864. };
  43865. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  43866. this._scene = scene;
  43867. };
  43868. CollisionCoordinatorLegacy.prototype.destroy = function () {
  43869. //Legacy need no destruction method.
  43870. };
  43871. //No update in legacy mode
  43872. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  43873. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  43874. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  43875. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  43876. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  43877. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  43878. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  43879. if (excludedMesh === void 0) { excludedMesh = null; }
  43880. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  43881. if (collider.retry >= maximumRetry) {
  43882. finalPosition.copyFrom(position);
  43883. return;
  43884. }
  43885. // Check if this is a mesh else camera or -1
  43886. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  43887. collider._initialize(position, velocity, closeDistance);
  43888. // Check all meshes
  43889. for (var index = 0; index < this._scene.meshes.length; index++) {
  43890. var mesh = this._scene.meshes[index];
  43891. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  43892. mesh._checkCollision(collider);
  43893. }
  43894. }
  43895. if (!collider.collisionFound) {
  43896. position.addToRef(velocity, finalPosition);
  43897. return;
  43898. }
  43899. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  43900. collider._getResponse(position, velocity);
  43901. }
  43902. if (velocity.length() <= closeDistance) {
  43903. finalPosition.copyFrom(position);
  43904. return;
  43905. }
  43906. collider.retry++;
  43907. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  43908. };
  43909. return CollisionCoordinatorLegacy;
  43910. }());
  43911. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  43912. })(BABYLON || (BABYLON = {}));
  43913. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  43914. var BABYLON;
  43915. (function (BABYLON) {
  43916. var Particle = /** @class */ (function () {
  43917. function Particle(particleSystem) {
  43918. this.particleSystem = particleSystem;
  43919. this.position = BABYLON.Vector3.Zero();
  43920. this.direction = BABYLON.Vector3.Zero();
  43921. this.color = new BABYLON.Color4(0, 0, 0, 0);
  43922. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  43923. this.lifeTime = 1.0;
  43924. this.age = 0;
  43925. this.size = 0;
  43926. this.angle = 0;
  43927. this.angularSpeed = 0;
  43928. this._currentFrameCounter = 0;
  43929. this.cellIndex = 0;
  43930. if (!this.particleSystem.isAnimationSheetEnabled) {
  43931. return;
  43932. }
  43933. this.cellIndex = this.particleSystem.startSpriteCellID;
  43934. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  43935. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  43936. }
  43937. else {
  43938. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  43939. }
  43940. }
  43941. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  43942. // (ageOffset / scaledUpdateSpeed) / available cells
  43943. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  43944. this._currentFrameCounter += scaledUpdateSpeed;
  43945. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  43946. this._currentFrameCounter = 0;
  43947. this.cellIndex++;
  43948. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43949. this.cellIndex = this.particleSystem.endSpriteCellID;
  43950. }
  43951. }
  43952. };
  43953. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  43954. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  43955. this.cellIndex++;
  43956. this._currentFrameCounter = 0;
  43957. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  43958. if (this.particleSystem.spriteCellLoop) {
  43959. this.cellIndex = this.particleSystem.startSpriteCellID;
  43960. }
  43961. else {
  43962. this.cellIndex = this.particleSystem.endSpriteCellID;
  43963. }
  43964. }
  43965. }
  43966. else {
  43967. this._currentFrameCounter++;
  43968. }
  43969. };
  43970. Particle.prototype.copyTo = function (other) {
  43971. other.position.copyFrom(this.position);
  43972. other.direction.copyFrom(this.direction);
  43973. other.color.copyFrom(this.color);
  43974. other.colorStep.copyFrom(this.colorStep);
  43975. other.lifeTime = this.lifeTime;
  43976. other.age = this.age;
  43977. other.size = this.size;
  43978. other.angle = this.angle;
  43979. other.angularSpeed = this.angularSpeed;
  43980. other.particleSystem = this.particleSystem;
  43981. other.cellIndex = this.cellIndex;
  43982. };
  43983. return Particle;
  43984. }());
  43985. BABYLON.Particle = Particle;
  43986. })(BABYLON || (BABYLON = {}));
  43987. //# sourceMappingURL=babylon.particle.js.map
  43988. var BABYLON;
  43989. (function (BABYLON) {
  43990. var randomNumber = function (min, max) {
  43991. if (min === max) {
  43992. return (min);
  43993. }
  43994. var random = Math.random();
  43995. return ((random * (max - min)) + min);
  43996. };
  43997. var ParticleSystem = /** @class */ (function () {
  43998. // end of sheet animation
  43999. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  44000. if (customEffect === void 0) { customEffect = null; }
  44001. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  44002. if (epsilon === void 0) { epsilon = 0.01; }
  44003. var _this = this;
  44004. this.name = name;
  44005. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  44006. // Members
  44007. this.animations = [];
  44008. this.renderingGroupId = 0;
  44009. this.emitter = null;
  44010. this.emitRate = 10;
  44011. this.manualEmitCount = -1;
  44012. this.updateSpeed = 0.01;
  44013. this.targetStopDuration = 0;
  44014. this.disposeOnStop = false;
  44015. this.minEmitPower = 1;
  44016. this.maxEmitPower = 1;
  44017. this.minLifeTime = 1;
  44018. this.maxLifeTime = 1;
  44019. this.minSize = 1;
  44020. this.maxSize = 1;
  44021. this.minAngularSpeed = 0;
  44022. this.maxAngularSpeed = 0;
  44023. this.layerMask = 0x0FFFFFFF;
  44024. this.customShader = null;
  44025. this.preventAutoStart = false;
  44026. /**
  44027. * An event triggered when the system is disposed.
  44028. * @type {BABYLON.Observable}
  44029. */
  44030. this.onDisposeObservable = new BABYLON.Observable();
  44031. this.onAnimationEnd = null;
  44032. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  44033. this.forceDepthWrite = false;
  44034. this.gravity = BABYLON.Vector3.Zero();
  44035. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  44036. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  44037. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  44038. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44039. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44040. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44041. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  44042. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44043. this.particles = new Array();
  44044. this._stockParticles = new Array();
  44045. this._newPartsExcess = 0;
  44046. this._vertexBuffers = {};
  44047. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  44048. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  44049. this._scaledDirection = BABYLON.Vector3.Zero();
  44050. this._scaledGravity = BABYLON.Vector3.Zero();
  44051. this._currentRenderId = -1;
  44052. this._started = false;
  44053. this._stopped = false;
  44054. this._actualFrame = 0;
  44055. // sheet animation
  44056. this.startSpriteCellID = 0;
  44057. this.endSpriteCellID = 0;
  44058. this.spriteCellLoop = true;
  44059. this.spriteCellChangeSpeed = 0;
  44060. this.spriteCellWidth = 0;
  44061. this.spriteCellHeight = 0;
  44062. this._vertexBufferSize = 11;
  44063. this.appendParticleVertexes = null;
  44064. this.id = name;
  44065. this._capacity = capacity;
  44066. this._epsilon = epsilon;
  44067. if (_isAnimationSheetEnabled) {
  44068. this._vertexBufferSize = 12;
  44069. }
  44070. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44071. this._customEffect = customEffect;
  44072. scene.particleSystems.push(this);
  44073. this._createIndexBuffer();
  44074. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  44075. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  44076. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  44077. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  44078. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  44079. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  44080. if (this._isAnimationSheetEnabled) {
  44081. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  44082. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  44083. }
  44084. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44085. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44086. this._vertexBuffers["options"] = options;
  44087. // Default behaviors
  44088. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  44089. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  44090. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  44091. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  44092. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  44093. };
  44094. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  44095. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  44096. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  44097. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  44098. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  44099. };
  44100. this.updateFunction = function (particles) {
  44101. for (var index = 0; index < particles.length; index++) {
  44102. var particle = particles[index];
  44103. particle.age += _this._scaledUpdateSpeed;
  44104. if (particle.age >= particle.lifeTime) {
  44105. _this.recycleParticle(particle);
  44106. index--;
  44107. continue;
  44108. }
  44109. else {
  44110. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  44111. particle.color.addInPlace(_this._scaledColorStep);
  44112. if (particle.color.a < 0)
  44113. particle.color.a = 0;
  44114. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  44115. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  44116. particle.position.addInPlace(_this._scaledDirection);
  44117. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  44118. particle.direction.addInPlace(_this._scaledGravity);
  44119. if (_this._isAnimationSheetEnabled) {
  44120. particle.updateCellIndex(_this._scaledUpdateSpeed);
  44121. }
  44122. }
  44123. }
  44124. };
  44125. }
  44126. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  44127. set: function (callback) {
  44128. if (this._onDisposeObserver) {
  44129. this.onDisposeObservable.remove(this._onDisposeObserver);
  44130. }
  44131. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44132. },
  44133. enumerable: true,
  44134. configurable: true
  44135. });
  44136. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  44137. get: function () {
  44138. return this._isAnimationSheetEnabled;
  44139. },
  44140. enumerable: true,
  44141. configurable: true
  44142. });
  44143. ParticleSystem.prototype._createIndexBuffer = function () {
  44144. var indices = [];
  44145. var index = 0;
  44146. for (var count = 0; count < this._capacity; count++) {
  44147. indices.push(index);
  44148. indices.push(index + 1);
  44149. indices.push(index + 2);
  44150. indices.push(index);
  44151. indices.push(index + 2);
  44152. indices.push(index + 3);
  44153. index += 4;
  44154. }
  44155. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  44156. };
  44157. ParticleSystem.prototype.recycleParticle = function (particle) {
  44158. var lastParticle = this.particles.pop();
  44159. if (lastParticle !== particle) {
  44160. lastParticle.copyTo(particle);
  44161. this._stockParticles.push(lastParticle);
  44162. }
  44163. };
  44164. ParticleSystem.prototype.getCapacity = function () {
  44165. return this._capacity;
  44166. };
  44167. ParticleSystem.prototype.isAlive = function () {
  44168. return this._alive;
  44169. };
  44170. ParticleSystem.prototype.isStarted = function () {
  44171. return this._started;
  44172. };
  44173. ParticleSystem.prototype.start = function () {
  44174. this._started = true;
  44175. this._stopped = false;
  44176. this._actualFrame = 0;
  44177. };
  44178. ParticleSystem.prototype.stop = function () {
  44179. this._stopped = true;
  44180. };
  44181. // animation sheet
  44182. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  44183. var offset = index * this._vertexBufferSize;
  44184. this._vertexData[offset] = particle.position.x;
  44185. this._vertexData[offset + 1] = particle.position.y;
  44186. this._vertexData[offset + 2] = particle.position.z;
  44187. this._vertexData[offset + 3] = particle.color.r;
  44188. this._vertexData[offset + 4] = particle.color.g;
  44189. this._vertexData[offset + 5] = particle.color.b;
  44190. this._vertexData[offset + 6] = particle.color.a;
  44191. this._vertexData[offset + 7] = particle.angle;
  44192. this._vertexData[offset + 8] = particle.size;
  44193. this._vertexData[offset + 9] = offsetX;
  44194. this._vertexData[offset + 10] = offsetY;
  44195. };
  44196. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  44197. if (offsetX === 0)
  44198. offsetX = this._epsilon;
  44199. else if (offsetX === 1)
  44200. offsetX = 1 - this._epsilon;
  44201. if (offsetY === 0)
  44202. offsetY = this._epsilon;
  44203. else if (offsetY === 1)
  44204. offsetY = 1 - this._epsilon;
  44205. var offset = index * this._vertexBufferSize;
  44206. this._vertexData[offset] = particle.position.x;
  44207. this._vertexData[offset + 1] = particle.position.y;
  44208. this._vertexData[offset + 2] = particle.position.z;
  44209. this._vertexData[offset + 3] = particle.color.r;
  44210. this._vertexData[offset + 4] = particle.color.g;
  44211. this._vertexData[offset + 5] = particle.color.b;
  44212. this._vertexData[offset + 6] = particle.color.a;
  44213. this._vertexData[offset + 7] = particle.angle;
  44214. this._vertexData[offset + 8] = particle.size;
  44215. this._vertexData[offset + 9] = offsetX;
  44216. this._vertexData[offset + 10] = offsetY;
  44217. this._vertexData[offset + 11] = particle.cellIndex;
  44218. };
  44219. ParticleSystem.prototype._update = function (newParticles) {
  44220. // Update current
  44221. this._alive = this.particles.length > 0;
  44222. this.updateFunction(this.particles);
  44223. // Add new ones
  44224. var worldMatrix;
  44225. if (this.emitter.position) {
  44226. var emitterMesh = this.emitter;
  44227. worldMatrix = emitterMesh.getWorldMatrix();
  44228. }
  44229. else {
  44230. var emitterPosition = this.emitter;
  44231. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  44232. }
  44233. var particle;
  44234. for (var index = 0; index < newParticles; index++) {
  44235. if (this.particles.length === this._capacity) {
  44236. break;
  44237. }
  44238. if (this._stockParticles.length !== 0) {
  44239. particle = this._stockParticles.pop();
  44240. particle.age = 0;
  44241. particle.cellIndex = this.startSpriteCellID;
  44242. }
  44243. else {
  44244. particle = new BABYLON.Particle(this);
  44245. }
  44246. this.particles.push(particle);
  44247. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  44248. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  44249. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  44250. particle.size = randomNumber(this.minSize, this.maxSize);
  44251. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  44252. this.startPositionFunction(worldMatrix, particle.position, particle);
  44253. var step = randomNumber(0, 1.0);
  44254. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  44255. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  44256. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  44257. }
  44258. };
  44259. ParticleSystem.prototype._getEffect = function () {
  44260. if (this._customEffect) {
  44261. return this._customEffect;
  44262. }
  44263. ;
  44264. var defines = [];
  44265. if (this._scene.clipPlane) {
  44266. defines.push("#define CLIPPLANE");
  44267. }
  44268. if (this._isAnimationSheetEnabled) {
  44269. defines.push("#define ANIMATESHEET");
  44270. }
  44271. // Effect
  44272. var join = defines.join("\n");
  44273. if (this._cachedDefines !== join) {
  44274. this._cachedDefines = join;
  44275. var attributesNamesOrOptions;
  44276. var effectCreationOption;
  44277. if (this._isAnimationSheetEnabled) {
  44278. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  44279. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  44280. }
  44281. else {
  44282. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  44283. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  44284. }
  44285. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  44286. }
  44287. return this._effect;
  44288. };
  44289. ParticleSystem.prototype.animate = function () {
  44290. if (!this._started)
  44291. return;
  44292. var effect = this._getEffect();
  44293. // Check
  44294. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  44295. return;
  44296. if (this._currentRenderId === this._scene.getRenderId()) {
  44297. return;
  44298. }
  44299. this._currentRenderId = this._scene.getRenderId();
  44300. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  44301. // determine the number of particles we need to create
  44302. var newParticles;
  44303. if (this.manualEmitCount > -1) {
  44304. newParticles = this.manualEmitCount;
  44305. this._newPartsExcess = 0;
  44306. this.manualEmitCount = 0;
  44307. }
  44308. else {
  44309. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  44310. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  44311. }
  44312. if (this._newPartsExcess > 1.0) {
  44313. newParticles += this._newPartsExcess >> 0;
  44314. this._newPartsExcess -= this._newPartsExcess >> 0;
  44315. }
  44316. this._alive = false;
  44317. if (!this._stopped) {
  44318. this._actualFrame += this._scaledUpdateSpeed;
  44319. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  44320. this.stop();
  44321. }
  44322. else {
  44323. newParticles = 0;
  44324. }
  44325. this._update(newParticles);
  44326. // Stopped?
  44327. if (this._stopped) {
  44328. if (!this._alive) {
  44329. this._started = false;
  44330. if (this.onAnimationEnd) {
  44331. this.onAnimationEnd();
  44332. }
  44333. if (this.disposeOnStop) {
  44334. this._scene._toBeDisposed.push(this);
  44335. }
  44336. }
  44337. }
  44338. // Animation sheet
  44339. if (this._isAnimationSheetEnabled) {
  44340. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  44341. }
  44342. else {
  44343. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  44344. }
  44345. // Update VBO
  44346. var offset = 0;
  44347. for (var index = 0; index < this.particles.length; index++) {
  44348. var particle = this.particles[index];
  44349. this.appendParticleVertexes(offset, particle);
  44350. offset += 4;
  44351. }
  44352. if (this._vertexBuffer) {
  44353. this._vertexBuffer.update(this._vertexData);
  44354. }
  44355. };
  44356. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  44357. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  44358. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  44359. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  44360. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  44361. };
  44362. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  44363. this._appendParticleVertex(offset++, particle, 0, 0);
  44364. this._appendParticleVertex(offset++, particle, 1, 0);
  44365. this._appendParticleVertex(offset++, particle, 1, 1);
  44366. this._appendParticleVertex(offset++, particle, 0, 1);
  44367. };
  44368. ParticleSystem.prototype.rebuild = function () {
  44369. this._createIndexBuffer();
  44370. if (this._vertexBuffer) {
  44371. this._vertexBuffer._rebuild();
  44372. }
  44373. };
  44374. ParticleSystem.prototype.render = function () {
  44375. var effect = this._getEffect();
  44376. // Check
  44377. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  44378. return 0;
  44379. var engine = this._scene.getEngine();
  44380. // Render
  44381. engine.enableEffect(effect);
  44382. engine.setState(false);
  44383. var viewMatrix = this._scene.getViewMatrix();
  44384. effect.setTexture("diffuseSampler", this.particleTexture);
  44385. effect.setMatrix("view", viewMatrix);
  44386. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44387. if (this._isAnimationSheetEnabled) {
  44388. var baseSize = this.particleTexture.getBaseSize();
  44389. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  44390. }
  44391. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  44392. if (this._scene.clipPlane) {
  44393. var clipPlane = this._scene.clipPlane;
  44394. var invView = viewMatrix.clone();
  44395. invView.invert();
  44396. effect.setMatrix("invView", invView);
  44397. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  44398. }
  44399. // VBOs
  44400. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44401. // Draw order
  44402. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  44403. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  44404. }
  44405. else {
  44406. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44407. }
  44408. if (this.forceDepthWrite) {
  44409. engine.setDepthWrite(true);
  44410. }
  44411. engine.draw(true, 0, this.particles.length * 6);
  44412. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44413. return this.particles.length;
  44414. };
  44415. ParticleSystem.prototype.dispose = function () {
  44416. if (this._vertexBuffer) {
  44417. this._vertexBuffer.dispose();
  44418. this._vertexBuffer = null;
  44419. }
  44420. if (this._indexBuffer) {
  44421. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44422. this._indexBuffer = null;
  44423. }
  44424. if (this.particleTexture) {
  44425. this.particleTexture.dispose();
  44426. this.particleTexture = null;
  44427. }
  44428. // Remove from scene
  44429. var index = this._scene.particleSystems.indexOf(this);
  44430. if (index > -1) {
  44431. this._scene.particleSystems.splice(index, 1);
  44432. }
  44433. // Callback
  44434. this.onDisposeObservable.notifyObservers(this);
  44435. this.onDisposeObservable.clear();
  44436. };
  44437. // Clone
  44438. ParticleSystem.prototype.clone = function (name, newEmitter) {
  44439. var custom = null;
  44440. var program = null;
  44441. if (this.customShader != null) {
  44442. program = this.customShader;
  44443. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44444. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44445. }
  44446. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  44447. result.customShader = program;
  44448. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  44449. if (newEmitter === undefined) {
  44450. newEmitter = this.emitter;
  44451. }
  44452. result.emitter = newEmitter;
  44453. if (this.particleTexture) {
  44454. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  44455. }
  44456. if (!this.preventAutoStart) {
  44457. result.start();
  44458. }
  44459. return result;
  44460. };
  44461. ParticleSystem.prototype.serialize = function () {
  44462. var serializationObject = {};
  44463. serializationObject.name = this.name;
  44464. serializationObject.id = this.id;
  44465. // Emitter
  44466. if (this.emitter.position) {
  44467. var emitterMesh = this.emitter;
  44468. serializationObject.emitterId = emitterMesh.id;
  44469. }
  44470. else {
  44471. var emitterPosition = this.emitter;
  44472. serializationObject.emitter = emitterPosition.asArray();
  44473. }
  44474. serializationObject.capacity = this.getCapacity();
  44475. if (this.particleTexture) {
  44476. serializationObject.textureName = this.particleTexture.name;
  44477. }
  44478. // Animations
  44479. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  44480. // Particle system
  44481. serializationObject.minAngularSpeed = this.minAngularSpeed;
  44482. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  44483. serializationObject.minSize = this.minSize;
  44484. serializationObject.maxSize = this.maxSize;
  44485. serializationObject.minEmitPower = this.minEmitPower;
  44486. serializationObject.maxEmitPower = this.maxEmitPower;
  44487. serializationObject.minLifeTime = this.minLifeTime;
  44488. serializationObject.maxLifeTime = this.maxLifeTime;
  44489. serializationObject.emitRate = this.emitRate;
  44490. serializationObject.minEmitBox = this.minEmitBox.asArray();
  44491. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  44492. serializationObject.gravity = this.gravity.asArray();
  44493. serializationObject.direction1 = this.direction1.asArray();
  44494. serializationObject.direction2 = this.direction2.asArray();
  44495. serializationObject.color1 = this.color1.asArray();
  44496. serializationObject.color2 = this.color2.asArray();
  44497. serializationObject.colorDead = this.colorDead.asArray();
  44498. serializationObject.updateSpeed = this.updateSpeed;
  44499. serializationObject.targetStopDuration = this.targetStopDuration;
  44500. serializationObject.textureMask = this.textureMask.asArray();
  44501. serializationObject.blendMode = this.blendMode;
  44502. serializationObject.customShader = this.customShader;
  44503. serializationObject.preventAutoStart = this.preventAutoStart;
  44504. return serializationObject;
  44505. };
  44506. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  44507. var name = parsedParticleSystem.name;
  44508. var custom = null;
  44509. var program = null;
  44510. if (parsedParticleSystem.customShader) {
  44511. program = parsedParticleSystem.customShader;
  44512. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  44513. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  44514. }
  44515. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  44516. particleSystem.customShader = program;
  44517. if (parsedParticleSystem.id) {
  44518. particleSystem.id = parsedParticleSystem.id;
  44519. }
  44520. // Auto start
  44521. if (parsedParticleSystem.preventAutoStart) {
  44522. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  44523. }
  44524. // Texture
  44525. if (parsedParticleSystem.textureName) {
  44526. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  44527. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  44528. }
  44529. // Emitter
  44530. if (parsedParticleSystem.emitterId) {
  44531. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  44532. }
  44533. else {
  44534. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  44535. }
  44536. // Animations
  44537. if (parsedParticleSystem.animations) {
  44538. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  44539. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  44540. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  44541. }
  44542. }
  44543. if (parsedParticleSystem.autoAnimate) {
  44544. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  44545. }
  44546. // Particle system
  44547. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  44548. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  44549. particleSystem.minSize = parsedParticleSystem.minSize;
  44550. particleSystem.maxSize = parsedParticleSystem.maxSize;
  44551. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  44552. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  44553. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  44554. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  44555. particleSystem.emitRate = parsedParticleSystem.emitRate;
  44556. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  44557. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  44558. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  44559. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  44560. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  44561. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  44562. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  44563. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  44564. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  44565. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  44566. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  44567. particleSystem.blendMode = parsedParticleSystem.blendMode;
  44568. if (!particleSystem.preventAutoStart) {
  44569. particleSystem.start();
  44570. }
  44571. return particleSystem;
  44572. };
  44573. // Statics
  44574. ParticleSystem.BLENDMODE_ONEONE = 0;
  44575. ParticleSystem.BLENDMODE_STANDARD = 1;
  44576. return ParticleSystem;
  44577. }());
  44578. BABYLON.ParticleSystem = ParticleSystem;
  44579. })(BABYLON || (BABYLON = {}));
  44580. //# sourceMappingURL=babylon.particleSystem.js.map
  44581. var BABYLON;
  44582. (function (BABYLON) {
  44583. var GPUParticleSystem = /** @class */ (function () {
  44584. function GPUParticleSystem(name, capacity, scene) {
  44585. this.name = name;
  44586. this.emitter = null;
  44587. this.renderingGroupId = 0;
  44588. this.layerMask = 0x0FFFFFFF; // TODO
  44589. this._updateVertexBuffers = {};
  44590. this._renderVertexBuffers = {};
  44591. this._currentRenderId = -1;
  44592. this._started = true;
  44593. /**
  44594. * An event triggered when the system is disposed.
  44595. * @type {BABYLON.Observable}
  44596. */
  44597. this.onDisposeObservable = new BABYLON.Observable();
  44598. this.id = name;
  44599. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44600. this._capacity = capacity;
  44601. this._engine = this._scene.getEngine();
  44602. this._scene.particleSystems.push(this);
  44603. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  44604. var updateEffectOptions = {
  44605. attributes: ["position", "age", "life", "velocity"],
  44606. uniformsNames: [],
  44607. uniformBuffersNames: [],
  44608. samplers: [],
  44609. defines: "",
  44610. fallbacks: null,
  44611. onCompiled: null,
  44612. onError: null,
  44613. indexParameters: null,
  44614. maxSimultaneousLights: 0,
  44615. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  44616. };
  44617. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  44618. }
  44619. GPUParticleSystem.prototype.isStarted = function () {
  44620. return this._started;
  44621. };
  44622. GPUParticleSystem.prototype.start = function () {
  44623. this._started = true;
  44624. };
  44625. GPUParticleSystem.prototype.stop = function () {
  44626. this._started = false;
  44627. };
  44628. GPUParticleSystem.prototype.animate = function () {
  44629. // Do nothing
  44630. };
  44631. GPUParticleSystem.prototype._initialize = function () {
  44632. if (this._renderVAO) {
  44633. return;
  44634. }
  44635. var data = new Array();
  44636. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  44637. // position
  44638. data.push(0.0);
  44639. data.push(0.0);
  44640. data.push(0.0);
  44641. var life = 1 + Math.random() * 10; // TODO: var
  44642. data.push(life + 1); // create the particle as a dead one to create a new one at start
  44643. data.push(life);
  44644. // velocity
  44645. data.push(0.0);
  44646. data.push(0.0);
  44647. data.push(0.0);
  44648. }
  44649. // Update VAO
  44650. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  44651. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  44652. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  44653. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  44654. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  44655. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  44656. this._engine.bindArrayBuffer(null);
  44657. // Render VAO
  44658. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  44659. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  44660. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  44661. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  44662. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  44663. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  44664. this._engine.bindArrayBuffer(null);
  44665. // Links
  44666. this._sourceVAO = this._updateVAO;
  44667. this._targetVAO = this._renderVAO;
  44668. this._sourceBuffer = this._updateBuffer;
  44669. this._targetBuffer = this._renderBuffer;
  44670. };
  44671. GPUParticleSystem.prototype.render = function () {
  44672. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  44673. return 0;
  44674. }
  44675. // Get everything ready to render
  44676. this._initialize();
  44677. if (this._currentRenderId === this._scene.getRenderId()) {
  44678. return 0;
  44679. }
  44680. this._currentRenderId = this._scene.getRenderId();
  44681. // Enable update effect
  44682. this._engine.enableEffect(this._updateEffect);
  44683. this._engine.setState(false);
  44684. // Bind source VAO
  44685. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  44686. // Update
  44687. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  44688. this._engine.setRasterizerState(false);
  44689. this._engine.beginTransformFeedback();
  44690. this._engine.drawPointClouds(0, this._capacity);
  44691. this._engine.endTransformFeedback();
  44692. this._engine.setRasterizerState(true);
  44693. this._engine.bindTransformFeedbackBuffer(null);
  44694. // Enable render effect
  44695. this._engine.enableEffect(this._renderEffect);
  44696. // Bind source VAO
  44697. this._engine.bindVertexArrayObject(this._targetVAO, null);
  44698. // Render
  44699. this._engine.drawPointClouds(0, this._capacity);
  44700. // Switch VAOs
  44701. var tmpVAO = this._sourceVAO;
  44702. this._sourceVAO = this._targetVAO;
  44703. this._targetVAO = tmpVAO;
  44704. // Switch buffers
  44705. var tmpBuffer = this._sourceBuffer;
  44706. this._sourceBuffer = this._targetBuffer;
  44707. this._targetBuffer = tmpBuffer;
  44708. return 0;
  44709. };
  44710. GPUParticleSystem.prototype.rebuild = function () {
  44711. };
  44712. GPUParticleSystem.prototype.dispose = function () {
  44713. var index = this._scene.particleSystems.indexOf(this);
  44714. if (index > -1) {
  44715. this._scene.particleSystems.splice(index, 1);
  44716. }
  44717. //TODO: this._dataBuffer.dispose();
  44718. // Callback
  44719. this.onDisposeObservable.notifyObservers(this);
  44720. this.onDisposeObservable.clear();
  44721. };
  44722. //TODO: Clone / Parse / serialize
  44723. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  44724. return null;
  44725. };
  44726. GPUParticleSystem.prototype.serialize = function () {
  44727. };
  44728. return GPUParticleSystem;
  44729. }());
  44730. BABYLON.GPUParticleSystem = GPUParticleSystem;
  44731. })(BABYLON || (BABYLON = {}));
  44732. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  44733. var BABYLON;
  44734. (function (BABYLON) {
  44735. var SolidParticle = /** @class */ (function () {
  44736. /**
  44737. * Creates a Solid Particle object.
  44738. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  44739. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  44740. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  44741. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  44742. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  44743. * `shapeId` (integer) is the model shape identifier in the SPS.
  44744. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  44745. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  44746. */
  44747. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  44748. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  44749. this.idx = 0; // particle global index
  44750. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  44751. this.position = BABYLON.Vector3.Zero(); // position
  44752. this.rotation = BABYLON.Vector3.Zero(); // rotation
  44753. this.scaling = BABYLON.Vector3.One(); // scaling
  44754. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  44755. this.velocity = BABYLON.Vector3.Zero(); // velocity
  44756. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  44757. this.alive = true; // alive
  44758. this.isVisible = true; // visibility
  44759. this._pos = 0; // index of this particle in the global "positions" array
  44760. this._ind = 0; // index of this particle in the global "indices" array
  44761. this.shapeId = 0; // model shape id
  44762. this.idxInShape = 0; // index of the particle in its shape id
  44763. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  44764. this.idx = particleIndex;
  44765. this._pos = positionIndex;
  44766. this._ind = indiceIndex;
  44767. this._model = model;
  44768. this.shapeId = shapeId;
  44769. this.idxInShape = idxInShape;
  44770. this._sps = sps;
  44771. if (modelBoundingInfo) {
  44772. this._modelBoundingInfo = modelBoundingInfo;
  44773. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  44774. }
  44775. }
  44776. Object.defineProperty(SolidParticle.prototype, "scale", {
  44777. /**
  44778. * legacy support, changed scale to scaling
  44779. */
  44780. get: function () {
  44781. return this.scaling;
  44782. },
  44783. set: function (scale) {
  44784. this.scaling = scale;
  44785. },
  44786. enumerable: true,
  44787. configurable: true
  44788. });
  44789. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  44790. /**
  44791. * legacy support, changed quaternion to rotationQuaternion
  44792. */
  44793. get: function () {
  44794. return this.rotationQuaternion;
  44795. },
  44796. set: function (q) {
  44797. this.rotationQuaternion = q;
  44798. },
  44799. enumerable: true,
  44800. configurable: true
  44801. });
  44802. /**
  44803. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  44804. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  44805. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  44806. */
  44807. SolidParticle.prototype.intersectsMesh = function (target) {
  44808. if (!this._boundingInfo || !target._boundingInfo) {
  44809. return false;
  44810. }
  44811. if (this._sps._bSphereOnly) {
  44812. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  44813. }
  44814. return this._boundingInfo.intersects(target._boundingInfo, false);
  44815. };
  44816. return SolidParticle;
  44817. }());
  44818. BABYLON.SolidParticle = SolidParticle;
  44819. var ModelShape = /** @class */ (function () {
  44820. /**
  44821. * 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.
  44822. * SPS internal tool, don't use it manually.
  44823. */
  44824. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  44825. this._indicesLength = 0; // length of the shape in the model indices array
  44826. this.shapeID = id;
  44827. this._shape = shape;
  44828. this._indicesLength = indicesLength;
  44829. this._shapeUV = shapeUV;
  44830. this._positionFunction = posFunction;
  44831. this._vertexFunction = vtxFunction;
  44832. }
  44833. return ModelShape;
  44834. }());
  44835. BABYLON.ModelShape = ModelShape;
  44836. var DepthSortedParticle = /** @class */ (function () {
  44837. function DepthSortedParticle() {
  44838. this.ind = 0; // index of the particle in the "indices" array
  44839. this.indicesLength = 0; // length of the particle shape in the "indices" array
  44840. this.sqDistance = 0.0; // squared distance from the particle to the camera
  44841. }
  44842. return DepthSortedParticle;
  44843. }());
  44844. BABYLON.DepthSortedParticle = DepthSortedParticle;
  44845. })(BABYLON || (BABYLON = {}));
  44846. //# sourceMappingURL=babylon.solidParticle.js.map
  44847. var BABYLON;
  44848. (function (BABYLON) {
  44849. /**
  44850. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  44851. */
  44852. var SolidParticleSystem = /** @class */ (function () {
  44853. /**
  44854. * Creates a SPS (Solid Particle System) object.
  44855. * `name` (String) is the SPS name, this will be the underlying mesh name.
  44856. * `scene` (Scene) is the scene in which the SPS is added.
  44857. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  44858. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  44859. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  44860. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  44861. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  44862. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  44863. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  44864. */
  44865. function SolidParticleSystem(name, scene, options) {
  44866. // public members
  44867. /**
  44868. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  44869. * Example : var p = SPS.particles[i];
  44870. */
  44871. this.particles = new Array();
  44872. /**
  44873. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  44874. */
  44875. this.nbParticles = 0;
  44876. /**
  44877. * If the particles must ever face the camera (default false). Useful for planar particles.
  44878. */
  44879. this.billboard = false;
  44880. /**
  44881. * Recompute normals when adding a shape
  44882. */
  44883. this.recomputeNormals = true;
  44884. /**
  44885. * This a counter ofr your own usage. It's not set by any SPS functions.
  44886. */
  44887. this.counter = 0;
  44888. /**
  44889. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  44890. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  44891. */
  44892. this.vars = {};
  44893. this._positions = new Array();
  44894. this._indices = new Array();
  44895. this._normals = new Array();
  44896. this._colors = new Array();
  44897. this._uvs = new Array();
  44898. this._index = 0; // indices index
  44899. this._updatable = true;
  44900. this._pickable = false;
  44901. this._isVisibilityBoxLocked = false;
  44902. this._alwaysVisible = false;
  44903. this._depthSort = false;
  44904. this._shapeCounter = 0;
  44905. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  44906. this._color = new BABYLON.Color4(0, 0, 0, 0);
  44907. this._computeParticleColor = true;
  44908. this._computeParticleTexture = true;
  44909. this._computeParticleRotation = true;
  44910. this._computeParticleVertex = false;
  44911. this._computeBoundingBox = false;
  44912. this._depthSortParticles = true;
  44913. this._cam_axisZ = BABYLON.Vector3.Zero();
  44914. this._cam_axisY = BABYLON.Vector3.Zero();
  44915. this._cam_axisX = BABYLON.Vector3.Zero();
  44916. this._axisZ = BABYLON.Axis.Z;
  44917. this._camDir = BABYLON.Vector3.Zero();
  44918. this._camInvertedPosition = BABYLON.Vector3.Zero();
  44919. this._rotMatrix = new BABYLON.Matrix();
  44920. this._invertMatrix = new BABYLON.Matrix();
  44921. this._rotated = BABYLON.Vector3.Zero();
  44922. this._quaternion = new BABYLON.Quaternion();
  44923. this._vertex = BABYLON.Vector3.Zero();
  44924. this._normal = BABYLON.Vector3.Zero();
  44925. this._yaw = 0.0;
  44926. this._pitch = 0.0;
  44927. this._roll = 0.0;
  44928. this._halfroll = 0.0;
  44929. this._halfpitch = 0.0;
  44930. this._halfyaw = 0.0;
  44931. this._sinRoll = 0.0;
  44932. this._cosRoll = 0.0;
  44933. this._sinPitch = 0.0;
  44934. this._cosPitch = 0.0;
  44935. this._sinYaw = 0.0;
  44936. this._cosYaw = 0.0;
  44937. this._mustUnrotateFixedNormals = false;
  44938. this._minimum = BABYLON.Tmp.Vector3[0];
  44939. this._maximum = BABYLON.Tmp.Vector3[1];
  44940. this._minBbox = BABYLON.Tmp.Vector3[4];
  44941. this._maxBbox = BABYLON.Tmp.Vector3[5];
  44942. this._particlesIntersect = false;
  44943. this._depthSortFunction = function (p1, p2) {
  44944. return (p2.sqDistance - p1.sqDistance);
  44945. };
  44946. this._needs32Bits = false;
  44947. this._bSphereOnly = false;
  44948. this._bSphereRadiusFactor = 1.0;
  44949. this.name = name;
  44950. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  44951. this._camera = scene.activeCamera;
  44952. this._pickable = options ? options.isPickable : false;
  44953. this._depthSort = options ? options.enableDepthSort : false;
  44954. this._particlesIntersect = options ? options.particleIntersection : false;
  44955. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  44956. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  44957. if (options && options.updatable) {
  44958. this._updatable = options.updatable;
  44959. }
  44960. else {
  44961. this._updatable = true;
  44962. }
  44963. if (this._pickable) {
  44964. this.pickedParticles = [];
  44965. }
  44966. if (this._depthSort) {
  44967. this.depthSortedParticles = [];
  44968. }
  44969. }
  44970. /**
  44971. * Builds the SPS underlying mesh. Returns a standard Mesh.
  44972. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  44973. */
  44974. SolidParticleSystem.prototype.buildMesh = function () {
  44975. if (this.nbParticles === 0) {
  44976. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  44977. this.addShape(triangle, 1);
  44978. triangle.dispose();
  44979. }
  44980. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  44981. this._positions32 = new Float32Array(this._positions);
  44982. this._uvs32 = new Float32Array(this._uvs);
  44983. this._colors32 = new Float32Array(this._colors);
  44984. if (this.recomputeNormals) {
  44985. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  44986. }
  44987. this._normals32 = new Float32Array(this._normals);
  44988. this._fixedNormal32 = new Float32Array(this._normals);
  44989. if (this._mustUnrotateFixedNormals) {
  44990. this._unrotateFixedNormals();
  44991. }
  44992. var vertexData = new BABYLON.VertexData();
  44993. vertexData.indices = this._indices32;
  44994. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  44995. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  44996. if (this._uvs32) {
  44997. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  44998. ;
  44999. }
  45000. if (this._colors32) {
  45001. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  45002. }
  45003. var mesh = new BABYLON.Mesh(this.name, this._scene);
  45004. vertexData.applyToMesh(mesh, this._updatable);
  45005. this.mesh = mesh;
  45006. this.mesh.isPickable = this._pickable;
  45007. // free memory
  45008. if (!this._depthSort) {
  45009. this._indices = null;
  45010. }
  45011. this._positions = null;
  45012. this._normals = null;
  45013. this._uvs = null;
  45014. this._colors = null;
  45015. if (!this._updatable) {
  45016. this.particles.length = 0;
  45017. }
  45018. return mesh;
  45019. };
  45020. /**
  45021. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  45022. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  45023. * Thus the particles generated from `digest()` have their property `position` set yet.
  45024. * `mesh` ( Mesh ) is the mesh to be digested
  45025. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  45026. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  45027. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  45028. */
  45029. SolidParticleSystem.prototype.digest = function (mesh, options) {
  45030. var size = (options && options.facetNb) || 1;
  45031. var number = (options && options.number) || 0;
  45032. var delta = (options && options.delta) || 0;
  45033. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45034. var meshInd = mesh.getIndices();
  45035. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45036. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45037. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45038. var f = 0; // facet counter
  45039. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  45040. // compute size from number
  45041. if (number) {
  45042. number = (number > totalFacets) ? totalFacets : number;
  45043. size = Math.round(totalFacets / number);
  45044. delta = 0;
  45045. }
  45046. else {
  45047. size = (size > totalFacets) ? totalFacets : size;
  45048. }
  45049. var facetPos = []; // submesh positions
  45050. var facetInd = []; // submesh indices
  45051. var facetUV = []; // submesh UV
  45052. var facetCol = []; // submesh colors
  45053. var barycenter = BABYLON.Tmp.Vector3[0];
  45054. var sizeO = size;
  45055. while (f < totalFacets) {
  45056. size = sizeO + Math.floor((1 + delta) * Math.random());
  45057. if (f > totalFacets - size) {
  45058. size = totalFacets - f;
  45059. }
  45060. // reset temp arrays
  45061. facetPos.length = 0;
  45062. facetInd.length = 0;
  45063. facetUV.length = 0;
  45064. facetCol.length = 0;
  45065. // iterate over "size" facets
  45066. var fi = 0;
  45067. for (var j = f * 3; j < (f + size) * 3; j++) {
  45068. facetInd.push(fi);
  45069. var i = meshInd[j];
  45070. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  45071. if (meshUV) {
  45072. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  45073. }
  45074. if (meshCol) {
  45075. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  45076. }
  45077. fi++;
  45078. }
  45079. // create a model shape for each single particle
  45080. var idx = this.nbParticles;
  45081. var shape = this._posToShape(facetPos);
  45082. var shapeUV = this._uvsToShapeUV(facetUV);
  45083. // compute the barycenter of the shape
  45084. var v;
  45085. for (v = 0; v < shape.length; v++) {
  45086. barycenter.addInPlace(shape[v]);
  45087. }
  45088. barycenter.scaleInPlace(1 / shape.length);
  45089. // shift the shape from its barycenter to the origin
  45090. for (v = 0; v < shape.length; v++) {
  45091. shape[v].subtractInPlace(barycenter);
  45092. }
  45093. var bInfo;
  45094. if (this._particlesIntersect) {
  45095. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  45096. }
  45097. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  45098. // add the particle in the SPS
  45099. var currentPos = this._positions.length;
  45100. var currentInd = this._indices.length;
  45101. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  45102. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  45103. // initialize the particle position
  45104. this.particles[this.nbParticles].position.addInPlace(barycenter);
  45105. this._index += shape.length;
  45106. idx++;
  45107. this.nbParticles++;
  45108. this._shapeCounter++;
  45109. f += size;
  45110. }
  45111. return this;
  45112. };
  45113. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  45114. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  45115. var index = 0;
  45116. var idx = 0;
  45117. for (var p = 0; p < this.particles.length; p++) {
  45118. this._particle = this.particles[p];
  45119. this._shape = this._particle._model._shape;
  45120. if (this._particle.rotationQuaternion) {
  45121. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45122. }
  45123. else {
  45124. this._yaw = this._particle.rotation.y;
  45125. this._pitch = this._particle.rotation.x;
  45126. this._roll = this._particle.rotation.z;
  45127. this._quaternionRotationYPR();
  45128. }
  45129. this._quaternionToRotationMatrix();
  45130. this._rotMatrix.invertToRef(this._invertMatrix);
  45131. for (var pt = 0; pt < this._shape.length; pt++) {
  45132. idx = index + pt * 3;
  45133. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  45134. this._fixedNormal32[idx] = this._normal.x;
  45135. this._fixedNormal32[idx + 1] = this._normal.y;
  45136. this._fixedNormal32[idx + 2] = this._normal.z;
  45137. }
  45138. index = idx + 3;
  45139. }
  45140. };
  45141. //reset copy
  45142. SolidParticleSystem.prototype._resetCopy = function () {
  45143. this._copy.position.x = 0;
  45144. this._copy.position.y = 0;
  45145. this._copy.position.z = 0;
  45146. this._copy.rotation.x = 0;
  45147. this._copy.rotation.y = 0;
  45148. this._copy.rotation.z = 0;
  45149. this._copy.rotationQuaternion = null;
  45150. this._copy.scaling.x = 1.0;
  45151. this._copy.scaling.y = 1.0;
  45152. this._copy.scaling.z = 1.0;
  45153. this._copy.uvs.x = 0;
  45154. this._copy.uvs.y = 0;
  45155. this._copy.uvs.z = 1.0;
  45156. this._copy.uvs.w = 1.0;
  45157. this._copy.color = null;
  45158. };
  45159. // _meshBuilder : inserts the shape model in the global SPS mesh
  45160. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  45161. var i;
  45162. var u = 0;
  45163. var c = 0;
  45164. var n = 0;
  45165. this._resetCopy();
  45166. if (options && options.positionFunction) {
  45167. options.positionFunction(this._copy, idx, idxInShape);
  45168. this._mustUnrotateFixedNormals = true;
  45169. }
  45170. if (this._copy.rotationQuaternion) {
  45171. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45172. }
  45173. else {
  45174. this._yaw = this._copy.rotation.y;
  45175. this._pitch = this._copy.rotation.x;
  45176. this._roll = this._copy.rotation.z;
  45177. this._quaternionRotationYPR();
  45178. }
  45179. this._quaternionToRotationMatrix();
  45180. for (i = 0; i < shape.length; i++) {
  45181. this._vertex.x = shape[i].x;
  45182. this._vertex.y = shape[i].y;
  45183. this._vertex.z = shape[i].z;
  45184. if (options && options.vertexFunction) {
  45185. options.vertexFunction(this._copy, this._vertex, i);
  45186. }
  45187. this._vertex.x *= this._copy.scaling.x;
  45188. this._vertex.y *= this._copy.scaling.y;
  45189. this._vertex.z *= this._copy.scaling.z;
  45190. this._vertex.x += this._copy.pivot.x;
  45191. this._vertex.y += this._copy.pivot.y;
  45192. this._vertex.z += this._copy.pivot.z;
  45193. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45194. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  45195. if (meshUV) {
  45196. 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);
  45197. u += 2;
  45198. }
  45199. if (this._copy.color) {
  45200. this._color = this._copy.color;
  45201. }
  45202. else if (meshCol && meshCol[c] !== undefined) {
  45203. this._color.r = meshCol[c];
  45204. this._color.g = meshCol[c + 1];
  45205. this._color.b = meshCol[c + 2];
  45206. this._color.a = meshCol[c + 3];
  45207. }
  45208. else {
  45209. this._color.r = 1.0;
  45210. this._color.g = 1.0;
  45211. this._color.b = 1.0;
  45212. this._color.a = 1.0;
  45213. }
  45214. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  45215. c += 4;
  45216. if (!this.recomputeNormals && meshNor) {
  45217. this._normal.x = meshNor[n];
  45218. this._normal.y = meshNor[n + 1];
  45219. this._normal.z = meshNor[n + 2];
  45220. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  45221. normals.push(this._normal.x, this._normal.y, this._normal.z);
  45222. n += 3;
  45223. }
  45224. }
  45225. for (i = 0; i < meshInd.length; i++) {
  45226. var current_ind = p + meshInd[i];
  45227. indices.push(current_ind);
  45228. if (current_ind > 65535) {
  45229. this._needs32Bits = true;
  45230. }
  45231. }
  45232. if (this._pickable) {
  45233. var nbfaces = meshInd.length / 3;
  45234. for (i = 0; i < nbfaces; i++) {
  45235. this.pickedParticles.push({ idx: idx, faceId: i });
  45236. }
  45237. }
  45238. if (this._depthSort) {
  45239. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  45240. }
  45241. return this._copy;
  45242. };
  45243. // returns a shape array from positions array
  45244. SolidParticleSystem.prototype._posToShape = function (positions) {
  45245. var shape = [];
  45246. for (var i = 0; i < positions.length; i += 3) {
  45247. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  45248. }
  45249. return shape;
  45250. };
  45251. // returns a shapeUV array from a Vector4 uvs
  45252. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  45253. var shapeUV = [];
  45254. if (uvs) {
  45255. for (var i = 0; i < uvs.length; i++)
  45256. shapeUV.push(uvs[i]);
  45257. }
  45258. return shapeUV;
  45259. };
  45260. // adds a new particle object in the particles array
  45261. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  45262. if (bInfo === void 0) { bInfo = null; }
  45263. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  45264. this.particles.push(sp);
  45265. return sp;
  45266. };
  45267. /**
  45268. * Adds some particles to the SPS from the model shape. Returns the shape id.
  45269. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  45270. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  45271. * `nb` (positive integer) the number of particles to be created from this model
  45272. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  45273. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  45274. */
  45275. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  45276. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45277. var meshInd = mesh.getIndices();
  45278. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45279. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  45280. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45281. var bbInfo;
  45282. if (this._particlesIntersect) {
  45283. bbInfo = mesh.getBoundingInfo();
  45284. }
  45285. var shape = this._posToShape(meshPos);
  45286. var shapeUV = this._uvsToShapeUV(meshUV);
  45287. var posfunc = options ? options.positionFunction : null;
  45288. var vtxfunc = options ? options.vertexFunction : null;
  45289. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  45290. // particles
  45291. var sp;
  45292. var currentCopy;
  45293. var idx = this.nbParticles;
  45294. for (var i = 0; i < nb; i++) {
  45295. var currentPos = this._positions.length;
  45296. var currentInd = this._indices.length;
  45297. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  45298. if (this._updatable) {
  45299. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  45300. sp.position.copyFrom(currentCopy.position);
  45301. sp.rotation.copyFrom(currentCopy.rotation);
  45302. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  45303. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  45304. }
  45305. if (currentCopy.color && sp.color) {
  45306. sp.color.copyFrom(currentCopy.color);
  45307. }
  45308. sp.scaling.copyFrom(currentCopy.scaling);
  45309. sp.uvs.copyFrom(currentCopy.uvs);
  45310. }
  45311. this._index += shape.length;
  45312. idx++;
  45313. }
  45314. this.nbParticles += nb;
  45315. this._shapeCounter++;
  45316. return this._shapeCounter - 1;
  45317. };
  45318. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  45319. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  45320. this._resetCopy();
  45321. if (particle._model._positionFunction) {
  45322. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  45323. }
  45324. if (this._copy.rotationQuaternion) {
  45325. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  45326. }
  45327. else {
  45328. this._yaw = this._copy.rotation.y;
  45329. this._pitch = this._copy.rotation.x;
  45330. this._roll = this._copy.rotation.z;
  45331. this._quaternionRotationYPR();
  45332. }
  45333. this._quaternionToRotationMatrix();
  45334. this._shape = particle._model._shape;
  45335. for (var pt = 0; pt < this._shape.length; pt++) {
  45336. this._vertex.x = this._shape[pt].x;
  45337. this._vertex.y = this._shape[pt].y;
  45338. this._vertex.z = this._shape[pt].z;
  45339. if (particle._model._vertexFunction) {
  45340. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  45341. }
  45342. this._vertex.x *= this._copy.scaling.x;
  45343. this._vertex.y *= this._copy.scaling.y;
  45344. this._vertex.z *= this._copy.scaling.z;
  45345. this._vertex.x += this._copy.pivot.x;
  45346. this._vertex.y += this._copy.pivot.y;
  45347. this._vertex.z += this._copy.pivot.z;
  45348. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  45349. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  45350. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  45351. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  45352. }
  45353. particle.position.x = 0.0;
  45354. particle.position.y = 0.0;
  45355. particle.position.z = 0.0;
  45356. particle.rotation.x = 0.0;
  45357. particle.rotation.y = 0.0;
  45358. particle.rotation.z = 0.0;
  45359. particle.rotationQuaternion = null;
  45360. particle.scaling.x = 1.0;
  45361. particle.scaling.y = 1.0;
  45362. particle.scaling.z = 1.0;
  45363. };
  45364. /**
  45365. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  45366. * Returns the SPS.
  45367. */
  45368. SolidParticleSystem.prototype.rebuildMesh = function () {
  45369. for (var p = 0; p < this.particles.length; p++) {
  45370. this._rebuildParticle(this.particles[p]);
  45371. }
  45372. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45373. return this;
  45374. };
  45375. /**
  45376. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  45377. * This method calls `updateParticle()` for each particle of the SPS.
  45378. * For an animated SPS, it is usually called within the render loop.
  45379. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  45380. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  45381. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  45382. * Returns the SPS.
  45383. */
  45384. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  45385. if (start === void 0) { start = 0; }
  45386. if (end === void 0) { end = this.nbParticles - 1; }
  45387. if (update === void 0) { update = true; }
  45388. if (!this._updatable) {
  45389. return this;
  45390. }
  45391. // custom beforeUpdate
  45392. this.beforeUpdateParticles(start, end, update);
  45393. this._cam_axisX.x = 1.0;
  45394. this._cam_axisX.y = 0.0;
  45395. this._cam_axisX.z = 0.0;
  45396. this._cam_axisY.x = 0.0;
  45397. this._cam_axisY.y = 1.0;
  45398. this._cam_axisY.z = 0.0;
  45399. this._cam_axisZ.x = 0.0;
  45400. this._cam_axisZ.y = 0.0;
  45401. this._cam_axisZ.z = 1.0;
  45402. // cases when the World Matrix is to be computed first
  45403. if (this.billboard || this._depthSort) {
  45404. this.mesh.computeWorldMatrix(true);
  45405. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  45406. }
  45407. // if the particles will always face the camera
  45408. if (this.billboard) {
  45409. // compute the camera position and un-rotate it by the current mesh rotation
  45410. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  45411. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  45412. this._cam_axisZ.normalize();
  45413. // same for camera up vector extracted from the cam view matrix
  45414. var view = this._camera.getViewMatrix(true);
  45415. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  45416. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  45417. this._cam_axisY.normalize();
  45418. this._cam_axisX.normalize();
  45419. }
  45420. // if depthSort, compute the camera global position in the mesh local system
  45421. if (this._depthSort) {
  45422. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  45423. }
  45424. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  45425. var idx = 0; // current position index in the global array positions32
  45426. var index = 0; // position start index in the global array positions32 of the current particle
  45427. var colidx = 0; // current color index in the global array colors32
  45428. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  45429. var uvidx = 0; // current uv index in the global array uvs32
  45430. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  45431. var pt = 0; // current index in the particle model shape
  45432. if (this.mesh.isFacetDataEnabled) {
  45433. this._computeBoundingBox = true;
  45434. }
  45435. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  45436. if (this._computeBoundingBox) {
  45437. if (start == 0 && end == this.nbParticles - 1) {
  45438. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  45439. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  45440. }
  45441. else {
  45442. if (this.mesh._boundingInfo) {
  45443. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  45444. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  45445. }
  45446. }
  45447. }
  45448. // particle loop
  45449. index = this.particles[start]._pos;
  45450. var vpos = (index / 3) | 0;
  45451. colorIndex = vpos * 4;
  45452. uvIndex = vpos * 2;
  45453. for (var p = start; p <= end; p++) {
  45454. this._particle = this.particles[p];
  45455. this._shape = this._particle._model._shape;
  45456. this._shapeUV = this._particle._model._shapeUV;
  45457. // call to custom user function to update the particle properties
  45458. this.updateParticle(this._particle);
  45459. // camera-particle distance for depth sorting
  45460. if (this._depthSort && this._depthSortParticles) {
  45461. var dsp = this.depthSortedParticles[p];
  45462. dsp.ind = this._particle._ind;
  45463. dsp.indicesLength = this._particle._model._indicesLength;
  45464. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  45465. }
  45466. // skip the computations for inactive or already invisible particles
  45467. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  45468. // increment indexes for the next particle
  45469. pt = this._shape.length;
  45470. index += pt * 3;
  45471. colorIndex += pt * 4;
  45472. uvIndex += pt * 2;
  45473. continue;
  45474. }
  45475. if (this._particle.isVisible) {
  45476. this._particle._stillInvisible = false; // un-mark permanent invisibility
  45477. // particle rotation matrix
  45478. if (this.billboard) {
  45479. this._particle.rotation.x = 0.0;
  45480. this._particle.rotation.y = 0.0;
  45481. }
  45482. if (this._computeParticleRotation || this.billboard) {
  45483. if (this._particle.rotationQuaternion) {
  45484. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  45485. }
  45486. else {
  45487. this._yaw = this._particle.rotation.y;
  45488. this._pitch = this._particle.rotation.x;
  45489. this._roll = this._particle.rotation.z;
  45490. this._quaternionRotationYPR();
  45491. }
  45492. this._quaternionToRotationMatrix();
  45493. }
  45494. // particle vertex loop
  45495. for (pt = 0; pt < this._shape.length; pt++) {
  45496. idx = index + pt * 3;
  45497. colidx = colorIndex + pt * 4;
  45498. uvidx = uvIndex + pt * 2;
  45499. this._vertex.x = this._shape[pt].x;
  45500. this._vertex.y = this._shape[pt].y;
  45501. this._vertex.z = this._shape[pt].z;
  45502. if (this._computeParticleVertex) {
  45503. this.updateParticleVertex(this._particle, this._vertex, pt);
  45504. }
  45505. // positions
  45506. this._vertex.x *= this._particle.scaling.x;
  45507. this._vertex.y *= this._particle.scaling.y;
  45508. this._vertex.z *= this._particle.scaling.z;
  45509. this._vertex.x += this._particle.pivot.x;
  45510. this._vertex.y += this._particle.pivot.y;
  45511. this._vertex.z += this._particle.pivot.z;
  45512. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45513. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45514. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45515. 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;
  45516. 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;
  45517. 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;
  45518. if (this._computeBoundingBox) {
  45519. if (this._positions32[idx] < this._minimum.x) {
  45520. this._minimum.x = this._positions32[idx];
  45521. }
  45522. if (this._positions32[idx] > this._maximum.x) {
  45523. this._maximum.x = this._positions32[idx];
  45524. }
  45525. if (this._positions32[idx + 1] < this._minimum.y) {
  45526. this._minimum.y = this._positions32[idx + 1];
  45527. }
  45528. if (this._positions32[idx + 1] > this._maximum.y) {
  45529. this._maximum.y = this._positions32[idx + 1];
  45530. }
  45531. if (this._positions32[idx + 2] < this._minimum.z) {
  45532. this._minimum.z = this._positions32[idx + 2];
  45533. }
  45534. if (this._positions32[idx + 2] > this._maximum.z) {
  45535. this._maximum.z = this._positions32[idx + 2];
  45536. }
  45537. }
  45538. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  45539. if (!this._computeParticleVertex) {
  45540. this._normal.x = this._fixedNormal32[idx];
  45541. this._normal.y = this._fixedNormal32[idx + 1];
  45542. this._normal.z = this._fixedNormal32[idx + 2];
  45543. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  45544. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  45545. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  45546. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  45547. 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;
  45548. 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;
  45549. }
  45550. if (this._computeParticleColor && this._particle.color) {
  45551. this._colors32[colidx] = this._particle.color.r;
  45552. this._colors32[colidx + 1] = this._particle.color.g;
  45553. this._colors32[colidx + 2] = this._particle.color.b;
  45554. this._colors32[colidx + 3] = this._particle.color.a;
  45555. }
  45556. if (this._computeParticleTexture) {
  45557. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45558. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45559. }
  45560. }
  45561. }
  45562. else {
  45563. this._particle._stillInvisible = true; // mark the particle as invisible
  45564. for (pt = 0; pt < this._shape.length; pt++) {
  45565. idx = index + pt * 3;
  45566. colidx = colorIndex + pt * 4;
  45567. uvidx = uvIndex + pt * 2;
  45568. this._positions32[idx] = 0.0;
  45569. this._positions32[idx + 1] = 0.0;
  45570. this._positions32[idx + 2] = 0.0;
  45571. this._normals32[idx] = 0.0;
  45572. this._normals32[idx + 1] = 0.0;
  45573. this._normals32[idx + 2] = 0.0;
  45574. if (this._computeParticleColor && this._particle.color) {
  45575. this._colors32[colidx] = this._particle.color.r;
  45576. this._colors32[colidx + 1] = this._particle.color.g;
  45577. this._colors32[colidx + 2] = this._particle.color.b;
  45578. this._colors32[colidx + 3] = this._particle.color.a;
  45579. }
  45580. if (this._computeParticleTexture) {
  45581. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  45582. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  45583. }
  45584. }
  45585. }
  45586. // if the particle intersections must be computed : update the bbInfo
  45587. if (this._particlesIntersect) {
  45588. var bInfo = this._particle._boundingInfo;
  45589. var bBox = bInfo.boundingBox;
  45590. var bSphere = bInfo.boundingSphere;
  45591. if (!this._bSphereOnly) {
  45592. // place, scale and rotate the particle bbox within the SPS local system, then update it
  45593. for (var b = 0; b < bBox.vectors.length; b++) {
  45594. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  45595. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  45596. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  45597. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  45598. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  45599. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  45600. 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;
  45601. 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;
  45602. 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;
  45603. }
  45604. bBox._update(this.mesh._worldMatrix);
  45605. }
  45606. // place and scale the particle bouding sphere in the SPS local system, then update it
  45607. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  45608. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  45609. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  45610. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  45611. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  45612. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  45613. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  45614. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  45615. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  45616. 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));
  45617. bSphere._update(this.mesh._worldMatrix);
  45618. }
  45619. // increment indexes for the next particle
  45620. index = idx + 3;
  45621. colorIndex = colidx + 4;
  45622. uvIndex = uvidx + 2;
  45623. }
  45624. // if the VBO must be updated
  45625. if (update) {
  45626. if (this._computeParticleColor) {
  45627. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  45628. }
  45629. if (this._computeParticleTexture) {
  45630. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  45631. }
  45632. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  45633. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  45634. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  45635. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  45636. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  45637. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  45638. for (var i = 0; i < this._normals32.length; i++) {
  45639. this._fixedNormal32[i] = this._normals32[i];
  45640. }
  45641. }
  45642. if (!this.mesh.areNormalsFrozen) {
  45643. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  45644. }
  45645. }
  45646. if (this._depthSort && this._depthSortParticles) {
  45647. this.depthSortedParticles.sort(this._depthSortFunction);
  45648. var dspl = this.depthSortedParticles.length;
  45649. var sorted = 0;
  45650. var lind = 0;
  45651. var sind = 0;
  45652. var sid = 0;
  45653. for (sorted = 0; sorted < dspl; sorted++) {
  45654. lind = this.depthSortedParticles[sorted].indicesLength;
  45655. sind = this.depthSortedParticles[sorted].ind;
  45656. for (var i = 0; i < lind; i++) {
  45657. this._indices32[sid] = this._indices[sind + i];
  45658. sid++;
  45659. }
  45660. }
  45661. this.mesh.updateIndices(this._indices32);
  45662. }
  45663. }
  45664. if (this._computeBoundingBox) {
  45665. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  45666. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  45667. }
  45668. this.afterUpdateParticles(start, end, update);
  45669. return this;
  45670. };
  45671. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  45672. this._halfroll = this._roll * 0.5;
  45673. this._halfpitch = this._pitch * 0.5;
  45674. this._halfyaw = this._yaw * 0.5;
  45675. this._sinRoll = Math.sin(this._halfroll);
  45676. this._cosRoll = Math.cos(this._halfroll);
  45677. this._sinPitch = Math.sin(this._halfpitch);
  45678. this._cosPitch = Math.cos(this._halfpitch);
  45679. this._sinYaw = Math.sin(this._halfyaw);
  45680. this._cosYaw = Math.cos(this._halfyaw);
  45681. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  45682. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  45683. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  45684. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  45685. };
  45686. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  45687. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  45688. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  45689. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  45690. this._rotMatrix.m[3] = 0;
  45691. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  45692. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  45693. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  45694. this._rotMatrix.m[7] = 0;
  45695. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  45696. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  45697. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  45698. this._rotMatrix.m[11] = 0;
  45699. this._rotMatrix.m[12] = 0;
  45700. this._rotMatrix.m[13] = 0;
  45701. this._rotMatrix.m[14] = 0;
  45702. this._rotMatrix.m[15] = 1.0;
  45703. };
  45704. /**
  45705. * Disposes the SPS.
  45706. * Returns nothing.
  45707. */
  45708. SolidParticleSystem.prototype.dispose = function () {
  45709. this.mesh.dispose();
  45710. this.vars = null;
  45711. // drop references to internal big arrays for the GC
  45712. this._positions = null;
  45713. this._indices = null;
  45714. this._normals = null;
  45715. this._uvs = null;
  45716. this._colors = null;
  45717. this._indices32 = null;
  45718. this._positions32 = null;
  45719. this._normals32 = null;
  45720. this._fixedNormal32 = null;
  45721. this._uvs32 = null;
  45722. this._colors32 = null;
  45723. this.pickedParticles = null;
  45724. };
  45725. /**
  45726. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  45727. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45728. * Returns the SPS.
  45729. */
  45730. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  45731. if (!this._isVisibilityBoxLocked) {
  45732. this.mesh.refreshBoundingInfo();
  45733. }
  45734. return this;
  45735. };
  45736. /**
  45737. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  45738. * @param size the size (float) of the visibility box
  45739. * note : this doesn't lock the SPS mesh bounding box.
  45740. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45741. */
  45742. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  45743. var vis = size / 2;
  45744. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  45745. };
  45746. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  45747. // getter and setter
  45748. get: function () {
  45749. return this._alwaysVisible;
  45750. },
  45751. /**
  45752. * Sets the SPS as always visible or not
  45753. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45754. */
  45755. set: function (val) {
  45756. this._alwaysVisible = val;
  45757. this.mesh.alwaysSelectAsActiveMesh = val;
  45758. },
  45759. enumerable: true,
  45760. configurable: true
  45761. });
  45762. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  45763. get: function () {
  45764. return this._isVisibilityBoxLocked;
  45765. },
  45766. /**
  45767. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  45768. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  45769. */
  45770. set: function (val) {
  45771. this._isVisibilityBoxLocked = val;
  45772. var boundingInfo = this.mesh.getBoundingInfo();
  45773. if (boundingInfo) {
  45774. boundingInfo.isLocked = val;
  45775. }
  45776. },
  45777. enumerable: true,
  45778. configurable: true
  45779. });
  45780. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  45781. // getters
  45782. get: function () {
  45783. return this._computeParticleRotation;
  45784. },
  45785. // Optimizer setters
  45786. /**
  45787. * Tells to `setParticles()` to compute the particle rotations or not.
  45788. * Default value : true. The SPS is faster when it's set to false.
  45789. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  45790. */
  45791. set: function (val) {
  45792. this._computeParticleRotation = val;
  45793. },
  45794. enumerable: true,
  45795. configurable: true
  45796. });
  45797. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  45798. get: function () {
  45799. return this._computeParticleColor;
  45800. },
  45801. /**
  45802. * Tells to `setParticles()` to compute the particle colors or not.
  45803. * Default value : true. The SPS is faster when it's set to false.
  45804. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  45805. */
  45806. set: function (val) {
  45807. this._computeParticleColor = val;
  45808. },
  45809. enumerable: true,
  45810. configurable: true
  45811. });
  45812. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  45813. get: function () {
  45814. return this._computeParticleTexture;
  45815. },
  45816. /**
  45817. * Tells to `setParticles()` to compute the particle textures or not.
  45818. * Default value : true. The SPS is faster when it's set to false.
  45819. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  45820. */
  45821. set: function (val) {
  45822. this._computeParticleTexture = val;
  45823. },
  45824. enumerable: true,
  45825. configurable: true
  45826. });
  45827. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  45828. get: function () {
  45829. return this._computeParticleVertex;
  45830. },
  45831. /**
  45832. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  45833. * Default value : false. The SPS is faster when it's set to false.
  45834. * Note : the particle custom vertex positions aren't stored values.
  45835. */
  45836. set: function (val) {
  45837. this._computeParticleVertex = val;
  45838. },
  45839. enumerable: true,
  45840. configurable: true
  45841. });
  45842. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  45843. get: function () {
  45844. return this._computeBoundingBox;
  45845. },
  45846. /**
  45847. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  45848. */
  45849. set: function (val) {
  45850. this._computeBoundingBox = val;
  45851. },
  45852. enumerable: true,
  45853. configurable: true
  45854. });
  45855. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  45856. get: function () {
  45857. return this._depthSortParticles;
  45858. },
  45859. /**
  45860. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  45861. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  45862. * Default : `true`
  45863. */
  45864. set: function (val) {
  45865. this._depthSortParticles = val;
  45866. },
  45867. enumerable: true,
  45868. configurable: true
  45869. });
  45870. // =======================================================================
  45871. // Particle behavior logic
  45872. // these following methods may be overwritten by the user to fit his needs
  45873. /**
  45874. * This function does nothing. It may be overwritten to set all the particle first values.
  45875. * The SPS doesn't call this function, you may have to call it by your own.
  45876. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45877. */
  45878. SolidParticleSystem.prototype.initParticles = function () {
  45879. };
  45880. /**
  45881. * This function does nothing. It may be overwritten to recycle a particle.
  45882. * The SPS doesn't call this function, you may have to call it by your own.
  45883. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45884. */
  45885. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  45886. return particle;
  45887. };
  45888. /**
  45889. * Updates a particle : this function should be overwritten by the user.
  45890. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  45891. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  45892. * ex : just set a particle position or velocity and recycle conditions
  45893. */
  45894. SolidParticleSystem.prototype.updateParticle = function (particle) {
  45895. return particle;
  45896. };
  45897. /**
  45898. * Updates a vertex of a particle : it can be overwritten by the user.
  45899. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  45900. * @param particle the current particle
  45901. * @param vertex the current index of the current particle
  45902. * @param pt the index of the current vertex in the particle shape
  45903. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  45904. * ex : just set a vertex particle position
  45905. */
  45906. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  45907. return vertex;
  45908. };
  45909. /**
  45910. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  45911. * This does nothing and may be overwritten by the user.
  45912. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45913. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45914. * @param update the boolean update value actually passed to setParticles()
  45915. */
  45916. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  45917. };
  45918. /**
  45919. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  45920. * This will be passed three parameters.
  45921. * This does nothing and may be overwritten by the user.
  45922. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45923. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  45924. * @param update the boolean update value actually passed to setParticles()
  45925. */
  45926. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  45927. };
  45928. return SolidParticleSystem;
  45929. }());
  45930. BABYLON.SolidParticleSystem = SolidParticleSystem;
  45931. })(BABYLON || (BABYLON = {}));
  45932. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  45933. var BABYLON;
  45934. (function (BABYLON) {
  45935. var GroundMesh = /** @class */ (function (_super) {
  45936. __extends(GroundMesh, _super);
  45937. function GroundMesh(name, scene) {
  45938. var _this = _super.call(this, name, scene) || this;
  45939. _this.generateOctree = false;
  45940. return _this;
  45941. }
  45942. GroundMesh.prototype.getClassName = function () {
  45943. return "GroundMesh";
  45944. };
  45945. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  45946. get: function () {
  45947. return Math.min(this._subdivisionsX, this._subdivisionsY);
  45948. },
  45949. enumerable: true,
  45950. configurable: true
  45951. });
  45952. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  45953. get: function () {
  45954. return this._subdivisionsX;
  45955. },
  45956. enumerable: true,
  45957. configurable: true
  45958. });
  45959. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  45960. get: function () {
  45961. return this._subdivisionsY;
  45962. },
  45963. enumerable: true,
  45964. configurable: true
  45965. });
  45966. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  45967. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  45968. this._subdivisionsX = chunksCount;
  45969. this._subdivisionsY = chunksCount;
  45970. this.subdivide(chunksCount);
  45971. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  45972. };
  45973. /**
  45974. * Returns a height (y) value in the Worl system :
  45975. * the ground altitude at the coordinates (x, z) expressed in the World system.
  45976. * Returns the ground y position if (x, z) are outside the ground surface.
  45977. */
  45978. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  45979. var world = this.getWorldMatrix();
  45980. var invMat = BABYLON.Tmp.Matrix[5];
  45981. world.invertToRef(invMat);
  45982. var tmpVect = BABYLON.Tmp.Vector3[8];
  45983. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  45984. x = tmpVect.x;
  45985. z = tmpVect.z;
  45986. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  45987. return this.position.y;
  45988. }
  45989. if (!this._heightQuads || this._heightQuads.length == 0) {
  45990. this._initHeightQuads();
  45991. this._computeHeightQuads();
  45992. }
  45993. var facet = this._getFacetAt(x, z);
  45994. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  45995. // return y in the World system
  45996. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  45997. return tmpVect.y;
  45998. };
  45999. /**
  46000. * Returns a normalized vector (Vector3) orthogonal to the ground
  46001. * at the ground coordinates (x, z) expressed in the World system.
  46002. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  46003. */
  46004. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  46005. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  46006. this.getNormalAtCoordinatesToRef(x, z, normal);
  46007. return normal;
  46008. };
  46009. /**
  46010. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  46011. * at the ground coordinates (x, z) expressed in the World system.
  46012. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  46013. * Returns the GroundMesh.
  46014. */
  46015. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  46016. var world = this.getWorldMatrix();
  46017. var tmpMat = BABYLON.Tmp.Matrix[5];
  46018. world.invertToRef(tmpMat);
  46019. var tmpVect = BABYLON.Tmp.Vector3[8];
  46020. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  46021. x = tmpVect.x;
  46022. z = tmpVect.z;
  46023. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  46024. return this;
  46025. }
  46026. if (!this._heightQuads || this._heightQuads.length == 0) {
  46027. this._initHeightQuads();
  46028. this._computeHeightQuads();
  46029. }
  46030. var facet = this._getFacetAt(x, z);
  46031. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  46032. return this;
  46033. };
  46034. /**
  46035. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  46036. * if the ground has been updated.
  46037. * This can be used in the render loop.
  46038. * Returns the GroundMesh.
  46039. */
  46040. GroundMesh.prototype.updateCoordinateHeights = function () {
  46041. if (!this._heightQuads || this._heightQuads.length == 0) {
  46042. this._initHeightQuads();
  46043. }
  46044. this._computeHeightQuads();
  46045. return this;
  46046. };
  46047. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  46048. GroundMesh.prototype._getFacetAt = function (x, z) {
  46049. // retrieve col and row from x, z coordinates in the ground local system
  46050. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  46051. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  46052. var quad = this._heightQuads[row * this._subdivisionsX + col];
  46053. var facet;
  46054. if (z < quad.slope.x * x + quad.slope.y) {
  46055. facet = quad.facet1;
  46056. }
  46057. else {
  46058. facet = quad.facet2;
  46059. }
  46060. return facet;
  46061. };
  46062. // Creates and populates the heightMap array with "facet" elements :
  46063. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  46064. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46065. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46066. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46067. // Returns the GroundMesh.
  46068. GroundMesh.prototype._initHeightQuads = function () {
  46069. var subdivisionsX = this._subdivisionsX;
  46070. var subdivisionsY = this._subdivisionsY;
  46071. this._heightQuads = new Array();
  46072. for (var row = 0; row < subdivisionsY; row++) {
  46073. for (var col = 0; col < subdivisionsX; col++) {
  46074. 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) };
  46075. this._heightQuads[row * subdivisionsX + col] = quad;
  46076. }
  46077. }
  46078. return this;
  46079. };
  46080. // Compute each quad element values and update the the heightMap array :
  46081. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  46082. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  46083. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  46084. // Returns the GroundMesh.
  46085. GroundMesh.prototype._computeHeightQuads = function () {
  46086. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46087. if (!positions) {
  46088. return this;
  46089. }
  46090. var v1 = BABYLON.Tmp.Vector3[3];
  46091. var v2 = BABYLON.Tmp.Vector3[2];
  46092. var v3 = BABYLON.Tmp.Vector3[1];
  46093. var v4 = BABYLON.Tmp.Vector3[0];
  46094. var v1v2 = BABYLON.Tmp.Vector3[4];
  46095. var v1v3 = BABYLON.Tmp.Vector3[5];
  46096. var v1v4 = BABYLON.Tmp.Vector3[6];
  46097. var norm1 = BABYLON.Tmp.Vector3[7];
  46098. var norm2 = BABYLON.Tmp.Vector3[8];
  46099. var i = 0;
  46100. var j = 0;
  46101. var k = 0;
  46102. var cd = 0; // 2D slope coefficient : z = cd * x + h
  46103. var h = 0;
  46104. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  46105. var d2 = 0;
  46106. var subdivisionsX = this._subdivisionsX;
  46107. var subdivisionsY = this._subdivisionsY;
  46108. for (var row = 0; row < subdivisionsY; row++) {
  46109. for (var col = 0; col < subdivisionsX; col++) {
  46110. i = col * 3;
  46111. j = row * (subdivisionsX + 1) * 3;
  46112. k = (row + 1) * (subdivisionsX + 1) * 3;
  46113. v1.x = positions[j + i];
  46114. v1.y = positions[j + i + 1];
  46115. v1.z = positions[j + i + 2];
  46116. v2.x = positions[j + i + 3];
  46117. v2.y = positions[j + i + 4];
  46118. v2.z = positions[j + i + 5];
  46119. v3.x = positions[k + i];
  46120. v3.y = positions[k + i + 1];
  46121. v3.z = positions[k + i + 2];
  46122. v4.x = positions[k + i + 3];
  46123. v4.y = positions[k + i + 4];
  46124. v4.z = positions[k + i + 5];
  46125. // 2D slope V1V4
  46126. cd = (v4.z - v1.z) / (v4.x - v1.x);
  46127. h = v1.z - cd * v1.x; // v1 belongs to the slope
  46128. // facet equations :
  46129. // we compute each facet normal vector
  46130. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  46131. // we compute the value d by applying the equation to v1 which belongs to the plane
  46132. // then we store the facet equation in a Vector4
  46133. v2.subtractToRef(v1, v1v2);
  46134. v3.subtractToRef(v1, v1v3);
  46135. v4.subtractToRef(v1, v1v4);
  46136. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  46137. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  46138. norm1.normalize();
  46139. norm2.normalize();
  46140. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  46141. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  46142. var quad = this._heightQuads[row * subdivisionsX + col];
  46143. quad.slope.copyFromFloats(cd, h);
  46144. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  46145. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  46146. }
  46147. }
  46148. return this;
  46149. };
  46150. GroundMesh.prototype.serialize = function (serializationObject) {
  46151. _super.prototype.serialize.call(this, serializationObject);
  46152. serializationObject.subdivisionsX = this._subdivisionsX;
  46153. serializationObject.subdivisionsY = this._subdivisionsY;
  46154. serializationObject.minX = this._minX;
  46155. serializationObject.maxX = this._maxX;
  46156. serializationObject.minZ = this._minZ;
  46157. serializationObject.maxZ = this._maxZ;
  46158. serializationObject.width = this._width;
  46159. serializationObject.height = this._height;
  46160. };
  46161. GroundMesh.Parse = function (parsedMesh, scene) {
  46162. var result = new GroundMesh(parsedMesh.name, scene);
  46163. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  46164. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  46165. result._minX = parsedMesh.minX;
  46166. result._maxX = parsedMesh.maxX;
  46167. result._minZ = parsedMesh.minZ;
  46168. result._maxZ = parsedMesh.maxZ;
  46169. result._width = parsedMesh.width;
  46170. result._height = parsedMesh.height;
  46171. return result;
  46172. };
  46173. return GroundMesh;
  46174. }(BABYLON.Mesh));
  46175. BABYLON.GroundMesh = GroundMesh;
  46176. })(BABYLON || (BABYLON = {}));
  46177. //# sourceMappingURL=babylon.groundMesh.js.map
  46178. var BABYLON;
  46179. (function (BABYLON) {
  46180. /**
  46181. * Creates an instance based on a source mesh.
  46182. */
  46183. var InstancedMesh = /** @class */ (function (_super) {
  46184. __extends(InstancedMesh, _super);
  46185. function InstancedMesh(name, source) {
  46186. var _this = _super.call(this, name, source.getScene()) || this;
  46187. source.instances.push(_this);
  46188. _this._sourceMesh = source;
  46189. _this.position.copyFrom(source.position);
  46190. _this.rotation.copyFrom(source.rotation);
  46191. _this.scaling.copyFrom(source.scaling);
  46192. if (source.rotationQuaternion) {
  46193. _this.rotationQuaternion = source.rotationQuaternion.clone();
  46194. }
  46195. _this.infiniteDistance = source.infiniteDistance;
  46196. _this.setPivotMatrix(source.getPivotMatrix());
  46197. _this.refreshBoundingInfo();
  46198. _this._syncSubMeshes();
  46199. return _this;
  46200. }
  46201. /**
  46202. * Returns the string "InstancedMesh".
  46203. */
  46204. InstancedMesh.prototype.getClassName = function () {
  46205. return "InstancedMesh";
  46206. };
  46207. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  46208. // Methods
  46209. get: function () {
  46210. return this._sourceMesh.receiveShadows;
  46211. },
  46212. enumerable: true,
  46213. configurable: true
  46214. });
  46215. Object.defineProperty(InstancedMesh.prototype, "material", {
  46216. get: function () {
  46217. return this._sourceMesh.material;
  46218. },
  46219. enumerable: true,
  46220. configurable: true
  46221. });
  46222. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  46223. get: function () {
  46224. return this._sourceMesh.visibility;
  46225. },
  46226. enumerable: true,
  46227. configurable: true
  46228. });
  46229. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  46230. get: function () {
  46231. return this._sourceMesh.skeleton;
  46232. },
  46233. enumerable: true,
  46234. configurable: true
  46235. });
  46236. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  46237. get: function () {
  46238. return this._sourceMesh.renderingGroupId;
  46239. },
  46240. enumerable: true,
  46241. configurable: true
  46242. });
  46243. /**
  46244. * Returns the total number of vertices (integer).
  46245. */
  46246. InstancedMesh.prototype.getTotalVertices = function () {
  46247. return this._sourceMesh.getTotalVertices();
  46248. };
  46249. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  46250. get: function () {
  46251. return this._sourceMesh;
  46252. },
  46253. enumerable: true,
  46254. configurable: true
  46255. });
  46256. /**
  46257. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  46258. */
  46259. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  46260. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  46261. };
  46262. /**
  46263. * Sets the vertex data of the mesh geometry for the requested `kind`.
  46264. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  46265. * The `data` are either a numeric array either a Float32Array.
  46266. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  46267. * 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).
  46268. * Note that a new underlying VertexBuffer object is created each call.
  46269. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  46270. *
  46271. * Possible `kind` values :
  46272. * - BABYLON.VertexBuffer.PositionKind
  46273. * - BABYLON.VertexBuffer.UVKind
  46274. * - BABYLON.VertexBuffer.UV2Kind
  46275. * - BABYLON.VertexBuffer.UV3Kind
  46276. * - BABYLON.VertexBuffer.UV4Kind
  46277. * - BABYLON.VertexBuffer.UV5Kind
  46278. * - BABYLON.VertexBuffer.UV6Kind
  46279. * - BABYLON.VertexBuffer.ColorKind
  46280. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46281. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46282. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46283. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46284. *
  46285. * Returns the Mesh.
  46286. */
  46287. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  46288. if (this.sourceMesh) {
  46289. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  46290. }
  46291. return this.sourceMesh;
  46292. };
  46293. /**
  46294. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  46295. * If the mesh has no geometry, it is simply returned as it is.
  46296. * The `data` are either a numeric array either a Float32Array.
  46297. * No new underlying VertexBuffer object is created.
  46298. * 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.
  46299. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  46300. *
  46301. * Possible `kind` values :
  46302. * - BABYLON.VertexBuffer.PositionKind
  46303. * - BABYLON.VertexBuffer.UVKind
  46304. * - BABYLON.VertexBuffer.UV2Kind
  46305. * - BABYLON.VertexBuffer.UV3Kind
  46306. * - BABYLON.VertexBuffer.UV4Kind
  46307. * - BABYLON.VertexBuffer.UV5Kind
  46308. * - BABYLON.VertexBuffer.UV6Kind
  46309. * - BABYLON.VertexBuffer.ColorKind
  46310. * - BABYLON.VertexBuffer.MatricesIndicesKind
  46311. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  46312. * - BABYLON.VertexBuffer.MatricesWeightsKind
  46313. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  46314. *
  46315. * Returns the Mesh.
  46316. */
  46317. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  46318. if (this.sourceMesh) {
  46319. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  46320. }
  46321. return this.sourceMesh;
  46322. };
  46323. /**
  46324. * Sets the mesh indices.
  46325. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  46326. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  46327. * This method creates a new index buffer each call.
  46328. * Returns the Mesh.
  46329. */
  46330. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  46331. if (totalVertices === void 0) { totalVertices = null; }
  46332. if (this.sourceMesh) {
  46333. this.sourceMesh.setIndices(indices, totalVertices);
  46334. }
  46335. return this.sourceMesh;
  46336. };
  46337. /**
  46338. * Boolean : True if the mesh owns the requested kind of data.
  46339. */
  46340. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  46341. return this._sourceMesh.isVerticesDataPresent(kind);
  46342. };
  46343. /**
  46344. * Returns an array of indices (IndicesArray).
  46345. */
  46346. InstancedMesh.prototype.getIndices = function () {
  46347. return this._sourceMesh.getIndices();
  46348. };
  46349. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  46350. get: function () {
  46351. return this._sourceMesh._positions;
  46352. },
  46353. enumerable: true,
  46354. configurable: true
  46355. });
  46356. /**
  46357. * Sets a new updated BoundingInfo to the mesh.
  46358. * Returns the mesh.
  46359. */
  46360. InstancedMesh.prototype.refreshBoundingInfo = function () {
  46361. var meshBB = this._sourceMesh.getBoundingInfo();
  46362. if (meshBB) {
  46363. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  46364. }
  46365. this._updateBoundingInfo();
  46366. return this;
  46367. };
  46368. InstancedMesh.prototype._preActivate = function () {
  46369. if (this._currentLOD) {
  46370. this._currentLOD._preActivate();
  46371. }
  46372. return this;
  46373. };
  46374. InstancedMesh.prototype._activate = function (renderId) {
  46375. if (this._currentLOD) {
  46376. this._currentLOD._registerInstanceForRenderId(this, renderId);
  46377. }
  46378. return this;
  46379. };
  46380. /**
  46381. * Returns the current associated LOD AbstractMesh.
  46382. */
  46383. InstancedMesh.prototype.getLOD = function (camera) {
  46384. if (!camera) {
  46385. return this;
  46386. }
  46387. var boundingInfo = this.getBoundingInfo();
  46388. if (!boundingInfo) {
  46389. return this;
  46390. }
  46391. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  46392. if (this._currentLOD === this.sourceMesh) {
  46393. return this;
  46394. }
  46395. return this._currentLOD;
  46396. };
  46397. InstancedMesh.prototype._syncSubMeshes = function () {
  46398. this.releaseSubMeshes();
  46399. if (this._sourceMesh.subMeshes) {
  46400. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  46401. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  46402. }
  46403. }
  46404. return this;
  46405. };
  46406. InstancedMesh.prototype._generatePointsArray = function () {
  46407. return this._sourceMesh._generatePointsArray();
  46408. };
  46409. /**
  46410. * Creates a new InstancedMesh from the current mesh.
  46411. * - name (string) : the cloned mesh name
  46412. * - newParent (optional Node) : the optional Node to parent the clone to.
  46413. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  46414. *
  46415. * Returns the clone.
  46416. */
  46417. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46418. var result = this._sourceMesh.createInstance(name);
  46419. // Deep copy
  46420. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  46421. // Bounding info
  46422. this.refreshBoundingInfo();
  46423. // Parent
  46424. if (newParent) {
  46425. result.parent = newParent;
  46426. }
  46427. if (!doNotCloneChildren) {
  46428. // Children
  46429. for (var index = 0; index < this.getScene().meshes.length; index++) {
  46430. var mesh = this.getScene().meshes[index];
  46431. if (mesh.parent === this) {
  46432. mesh.clone(mesh.name, result);
  46433. }
  46434. }
  46435. }
  46436. result.computeWorldMatrix(true);
  46437. return result;
  46438. };
  46439. /**
  46440. * Disposes the InstancedMesh.
  46441. * Returns nothing.
  46442. */
  46443. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  46444. // Remove from mesh
  46445. var index = this._sourceMesh.instances.indexOf(this);
  46446. this._sourceMesh.instances.splice(index, 1);
  46447. _super.prototype.dispose.call(this, doNotRecurse);
  46448. };
  46449. return InstancedMesh;
  46450. }(BABYLON.AbstractMesh));
  46451. BABYLON.InstancedMesh = InstancedMesh;
  46452. })(BABYLON || (BABYLON = {}));
  46453. //# sourceMappingURL=babylon.instancedMesh.js.map
  46454. var BABYLON;
  46455. (function (BABYLON) {
  46456. var LinesMesh = /** @class */ (function (_super) {
  46457. __extends(LinesMesh, _super);
  46458. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  46459. if (scene === void 0) { scene = null; }
  46460. if (parent === void 0) { parent = null; }
  46461. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  46462. _this.useVertexColor = useVertexColor;
  46463. _this.color = new BABYLON.Color3(1, 1, 1);
  46464. _this.alpha = 1;
  46465. if (source) {
  46466. _this.color = source.color.clone();
  46467. _this.alpha = source.alpha;
  46468. _this.useVertexColor = source.useVertexColor;
  46469. }
  46470. _this._intersectionThreshold = 0.1;
  46471. var options = {
  46472. attributes: [BABYLON.VertexBuffer.PositionKind],
  46473. uniforms: ["world", "viewProjection"],
  46474. needAlphaBlending: false,
  46475. };
  46476. if (!useVertexColor) {
  46477. options.uniforms.push("color");
  46478. options.needAlphaBlending = true;
  46479. }
  46480. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  46481. return _this;
  46482. }
  46483. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  46484. /**
  46485. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46486. * This margin is expressed in world space coordinates, so its value may vary.
  46487. * Default value is 0.1
  46488. * @returns the intersection Threshold value.
  46489. */
  46490. get: function () {
  46491. return this._intersectionThreshold;
  46492. },
  46493. /**
  46494. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  46495. * This margin is expressed in world space coordinates, so its value may vary.
  46496. * @param value the new threshold to apply
  46497. */
  46498. set: function (value) {
  46499. if (this._intersectionThreshold === value) {
  46500. return;
  46501. }
  46502. this._intersectionThreshold = value;
  46503. if (this.geometry) {
  46504. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  46505. }
  46506. },
  46507. enumerable: true,
  46508. configurable: true
  46509. });
  46510. /**
  46511. * Returns the string "LineMesh"
  46512. */
  46513. LinesMesh.prototype.getClassName = function () {
  46514. return "LinesMesh";
  46515. };
  46516. Object.defineProperty(LinesMesh.prototype, "material", {
  46517. get: function () {
  46518. return this._colorShader;
  46519. },
  46520. set: function (value) {
  46521. // Do nothing
  46522. },
  46523. enumerable: true,
  46524. configurable: true
  46525. });
  46526. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  46527. get: function () {
  46528. return false;
  46529. },
  46530. enumerable: true,
  46531. configurable: true
  46532. });
  46533. LinesMesh.prototype.createInstance = function (name) {
  46534. throw new Error("LinesMeshes do not support createInstance.");
  46535. };
  46536. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  46537. if (!this._geometry) {
  46538. return this;
  46539. }
  46540. // VBOs
  46541. this._geometry._bind(this._colorShader.getEffect());
  46542. // Color
  46543. if (!this.useVertexColor) {
  46544. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  46545. }
  46546. return this;
  46547. };
  46548. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  46549. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  46550. return this;
  46551. }
  46552. var engine = this.getScene().getEngine();
  46553. // Draw order
  46554. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  46555. return this;
  46556. };
  46557. LinesMesh.prototype.dispose = function (doNotRecurse) {
  46558. this._colorShader.dispose();
  46559. _super.prototype.dispose.call(this, doNotRecurse);
  46560. };
  46561. /**
  46562. * Returns a new LineMesh object cloned from the current one.
  46563. */
  46564. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  46565. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  46566. };
  46567. return LinesMesh;
  46568. }(BABYLON.Mesh));
  46569. BABYLON.LinesMesh = LinesMesh;
  46570. })(BABYLON || (BABYLON = {}));
  46571. //# sourceMappingURL=babylon.linesMesh.js.map
  46572. var BABYLON;
  46573. (function (BABYLON) {
  46574. var ShaderMaterial = /** @class */ (function (_super) {
  46575. __extends(ShaderMaterial, _super);
  46576. function ShaderMaterial(name, scene, shaderPath, options) {
  46577. var _this = _super.call(this, name, scene) || this;
  46578. _this._textures = {};
  46579. _this._textureArrays = {};
  46580. _this._floats = {};
  46581. _this._floatsArrays = {};
  46582. _this._colors3 = {};
  46583. _this._colors3Arrays = {};
  46584. _this._colors4 = {};
  46585. _this._vectors2 = {};
  46586. _this._vectors3 = {};
  46587. _this._vectors4 = {};
  46588. _this._matrices = {};
  46589. _this._matrices3x3 = {};
  46590. _this._matrices2x2 = {};
  46591. _this._vectors3Arrays = {};
  46592. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  46593. _this._shaderPath = shaderPath;
  46594. options.needAlphaBlending = options.needAlphaBlending || false;
  46595. options.needAlphaTesting = options.needAlphaTesting || false;
  46596. options.attributes = options.attributes || ["position", "normal", "uv"];
  46597. options.uniforms = options.uniforms || ["worldViewProjection"];
  46598. options.uniformBuffers = options.uniformBuffers || [];
  46599. options.samplers = options.samplers || [];
  46600. options.defines = options.defines || [];
  46601. _this._options = options;
  46602. return _this;
  46603. }
  46604. ShaderMaterial.prototype.getClassName = function () {
  46605. return "ShaderMaterial";
  46606. };
  46607. ShaderMaterial.prototype.needAlphaBlending = function () {
  46608. return this._options.needAlphaBlending;
  46609. };
  46610. ShaderMaterial.prototype.needAlphaTesting = function () {
  46611. return this._options.needAlphaTesting;
  46612. };
  46613. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  46614. if (this._options.uniforms.indexOf(uniformName) === -1) {
  46615. this._options.uniforms.push(uniformName);
  46616. }
  46617. };
  46618. ShaderMaterial.prototype.setTexture = function (name, texture) {
  46619. if (this._options.samplers.indexOf(name) === -1) {
  46620. this._options.samplers.push(name);
  46621. }
  46622. this._textures[name] = texture;
  46623. return this;
  46624. };
  46625. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  46626. if (this._options.samplers.indexOf(name) === -1) {
  46627. this._options.samplers.push(name);
  46628. }
  46629. this._checkUniform(name);
  46630. this._textureArrays[name] = textures;
  46631. return this;
  46632. };
  46633. ShaderMaterial.prototype.setFloat = function (name, value) {
  46634. this._checkUniform(name);
  46635. this._floats[name] = value;
  46636. return this;
  46637. };
  46638. ShaderMaterial.prototype.setFloats = function (name, value) {
  46639. this._checkUniform(name);
  46640. this._floatsArrays[name] = value;
  46641. return this;
  46642. };
  46643. ShaderMaterial.prototype.setColor3 = function (name, value) {
  46644. this._checkUniform(name);
  46645. this._colors3[name] = value;
  46646. return this;
  46647. };
  46648. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  46649. this._checkUniform(name);
  46650. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  46651. color.toArray(arr, arr.length);
  46652. return arr;
  46653. }, []);
  46654. return this;
  46655. };
  46656. ShaderMaterial.prototype.setColor4 = function (name, value) {
  46657. this._checkUniform(name);
  46658. this._colors4[name] = value;
  46659. return this;
  46660. };
  46661. ShaderMaterial.prototype.setVector2 = function (name, value) {
  46662. this._checkUniform(name);
  46663. this._vectors2[name] = value;
  46664. return this;
  46665. };
  46666. ShaderMaterial.prototype.setVector3 = function (name, value) {
  46667. this._checkUniform(name);
  46668. this._vectors3[name] = value;
  46669. return this;
  46670. };
  46671. ShaderMaterial.prototype.setVector4 = function (name, value) {
  46672. this._checkUniform(name);
  46673. this._vectors4[name] = value;
  46674. return this;
  46675. };
  46676. ShaderMaterial.prototype.setMatrix = function (name, value) {
  46677. this._checkUniform(name);
  46678. this._matrices[name] = value;
  46679. return this;
  46680. };
  46681. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  46682. this._checkUniform(name);
  46683. this._matrices3x3[name] = value;
  46684. return this;
  46685. };
  46686. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  46687. this._checkUniform(name);
  46688. this._matrices2x2[name] = value;
  46689. return this;
  46690. };
  46691. ShaderMaterial.prototype.setArray3 = function (name, value) {
  46692. this._checkUniform(name);
  46693. this._vectors3Arrays[name] = value;
  46694. return this;
  46695. };
  46696. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  46697. if (!mesh) {
  46698. return true;
  46699. }
  46700. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  46701. return false;
  46702. }
  46703. return false;
  46704. };
  46705. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  46706. var scene = this.getScene();
  46707. var engine = scene.getEngine();
  46708. if (!this.checkReadyOnEveryCall) {
  46709. if (this._renderId === scene.getRenderId()) {
  46710. if (this._checkCache(scene, mesh, useInstances)) {
  46711. return true;
  46712. }
  46713. }
  46714. }
  46715. // Instances
  46716. var defines = [];
  46717. var attribs = [];
  46718. var fallbacks = new BABYLON.EffectFallbacks();
  46719. if (useInstances) {
  46720. defines.push("#define INSTANCES");
  46721. }
  46722. for (var index = 0; index < this._options.defines.length; index++) {
  46723. defines.push(this._options.defines[index]);
  46724. }
  46725. for (var index = 0; index < this._options.attributes.length; index++) {
  46726. attribs.push(this._options.attributes[index]);
  46727. }
  46728. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  46729. attribs.push(BABYLON.VertexBuffer.ColorKind);
  46730. defines.push("#define VERTEXCOLOR");
  46731. }
  46732. // Bones
  46733. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  46734. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46735. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46736. if (mesh.numBoneInfluencers > 4) {
  46737. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46738. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46739. }
  46740. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46741. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46742. fallbacks.addCPUSkinningFallback(0, mesh);
  46743. if (this._options.uniforms.indexOf("mBones") === -1) {
  46744. this._options.uniforms.push("mBones");
  46745. }
  46746. }
  46747. else {
  46748. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46749. }
  46750. // Textures
  46751. for (var name in this._textures) {
  46752. if (!this._textures[name].isReady()) {
  46753. return false;
  46754. }
  46755. }
  46756. // Alpha test
  46757. if (engine.getAlphaTesting()) {
  46758. defines.push("#define ALPHATEST");
  46759. }
  46760. var previousEffect = this._effect;
  46761. var join = defines.join("\n");
  46762. this._effect = engine.createEffect(this._shaderPath, {
  46763. attributes: attribs,
  46764. uniformsNames: this._options.uniforms,
  46765. uniformBuffersNames: this._options.uniformBuffers,
  46766. samplers: this._options.samplers,
  46767. defines: join,
  46768. fallbacks: fallbacks,
  46769. onCompiled: this.onCompiled,
  46770. onError: this.onError
  46771. }, engine);
  46772. if (!this._effect.isReady()) {
  46773. return false;
  46774. }
  46775. if (previousEffect !== this._effect) {
  46776. scene.resetCachedMaterial();
  46777. }
  46778. this._renderId = scene.getRenderId();
  46779. return true;
  46780. };
  46781. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  46782. var scene = this.getScene();
  46783. if (!this._effect) {
  46784. return;
  46785. }
  46786. if (this._options.uniforms.indexOf("world") !== -1) {
  46787. this._effect.setMatrix("world", world);
  46788. }
  46789. if (this._options.uniforms.indexOf("worldView") !== -1) {
  46790. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  46791. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  46792. }
  46793. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  46794. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  46795. }
  46796. };
  46797. ShaderMaterial.prototype.bind = function (world, mesh) {
  46798. // Std values
  46799. this.bindOnlyWorldMatrix(world);
  46800. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  46801. if (this._options.uniforms.indexOf("view") !== -1) {
  46802. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  46803. }
  46804. if (this._options.uniforms.indexOf("projection") !== -1) {
  46805. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  46806. }
  46807. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  46808. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  46809. }
  46810. // Bones
  46811. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  46812. var name;
  46813. // Texture
  46814. for (name in this._textures) {
  46815. this._effect.setTexture(name, this._textures[name]);
  46816. }
  46817. // Texture arrays
  46818. for (name in this._textureArrays) {
  46819. this._effect.setTextureArray(name, this._textureArrays[name]);
  46820. }
  46821. // Float
  46822. for (name in this._floats) {
  46823. this._effect.setFloat(name, this._floats[name]);
  46824. }
  46825. // Float s
  46826. for (name in this._floatsArrays) {
  46827. this._effect.setArray(name, this._floatsArrays[name]);
  46828. }
  46829. // Color3
  46830. for (name in this._colors3) {
  46831. this._effect.setColor3(name, this._colors3[name]);
  46832. }
  46833. for (name in this._colors3Arrays) {
  46834. this._effect.setArray3(name, this._colors3Arrays[name]);
  46835. }
  46836. // Color4
  46837. for (name in this._colors4) {
  46838. var color = this._colors4[name];
  46839. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  46840. }
  46841. // Vector2
  46842. for (name in this._vectors2) {
  46843. this._effect.setVector2(name, this._vectors2[name]);
  46844. }
  46845. // Vector3
  46846. for (name in this._vectors3) {
  46847. this._effect.setVector3(name, this._vectors3[name]);
  46848. }
  46849. // Vector4
  46850. for (name in this._vectors4) {
  46851. this._effect.setVector4(name, this._vectors4[name]);
  46852. }
  46853. // Matrix
  46854. for (name in this._matrices) {
  46855. this._effect.setMatrix(name, this._matrices[name]);
  46856. }
  46857. // Matrix 3x3
  46858. for (name in this._matrices3x3) {
  46859. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  46860. }
  46861. // Matrix 2x2
  46862. for (name in this._matrices2x2) {
  46863. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  46864. }
  46865. // Vector3Array
  46866. for (name in this._vectors3Arrays) {
  46867. this._effect.setArray3(name, this._vectors3Arrays[name]);
  46868. }
  46869. }
  46870. this._afterBind(mesh);
  46871. };
  46872. ShaderMaterial.prototype.getActiveTextures = function () {
  46873. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46874. for (var name in this._textures) {
  46875. activeTextures.push(this._textures[name]);
  46876. }
  46877. for (var name in this._textureArrays) {
  46878. var array = this._textureArrays[name];
  46879. for (var index = 0; index < array.length; index++) {
  46880. activeTextures.push(array[index]);
  46881. }
  46882. }
  46883. return activeTextures;
  46884. };
  46885. ShaderMaterial.prototype.hasTexture = function (texture) {
  46886. if (_super.prototype.hasTexture.call(this, texture)) {
  46887. return true;
  46888. }
  46889. for (var name in this._textures) {
  46890. if (this._textures[name] === texture) {
  46891. return true;
  46892. }
  46893. }
  46894. for (var name in this._textureArrays) {
  46895. var array = this._textureArrays[name];
  46896. for (var index = 0; index < array.length; index++) {
  46897. if (array[index] === texture) {
  46898. return true;
  46899. }
  46900. }
  46901. }
  46902. return false;
  46903. };
  46904. ShaderMaterial.prototype.clone = function (name) {
  46905. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  46906. return newShaderMaterial;
  46907. };
  46908. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46909. if (forceDisposeTextures) {
  46910. var name;
  46911. for (name in this._textures) {
  46912. this._textures[name].dispose();
  46913. }
  46914. for (name in this._textureArrays) {
  46915. var array = this._textureArrays[name];
  46916. for (var index = 0; index < array.length; index++) {
  46917. array[index].dispose();
  46918. }
  46919. }
  46920. }
  46921. this._textures = {};
  46922. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46923. };
  46924. ShaderMaterial.prototype.serialize = function () {
  46925. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46926. serializationObject.customType = "BABYLON.ShaderMaterial";
  46927. serializationObject.options = this._options;
  46928. serializationObject.shaderPath = this._shaderPath;
  46929. var name;
  46930. // Texture
  46931. serializationObject.textures = {};
  46932. for (name in this._textures) {
  46933. serializationObject.textures[name] = this._textures[name].serialize();
  46934. }
  46935. // Texture arrays
  46936. serializationObject.textureArrays = {};
  46937. for (name in this._textureArrays) {
  46938. serializationObject.textureArrays[name] = [];
  46939. var array = this._textureArrays[name];
  46940. for (var index = 0; index < array.length; index++) {
  46941. serializationObject.textureArrays[name].push(array[index].serialize());
  46942. }
  46943. }
  46944. // Float
  46945. serializationObject.floats = {};
  46946. for (name in this._floats) {
  46947. serializationObject.floats[name] = this._floats[name];
  46948. }
  46949. // Float s
  46950. serializationObject.FloatArrays = {};
  46951. for (name in this._floatsArrays) {
  46952. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  46953. }
  46954. // Color3
  46955. serializationObject.colors3 = {};
  46956. for (name in this._colors3) {
  46957. serializationObject.colors3[name] = this._colors3[name].asArray();
  46958. }
  46959. // Color3 array
  46960. serializationObject.colors3Arrays = {};
  46961. for (name in this._colors3Arrays) {
  46962. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  46963. }
  46964. // Color4
  46965. serializationObject.colors4 = {};
  46966. for (name in this._colors4) {
  46967. serializationObject.colors4[name] = this._colors4[name].asArray();
  46968. }
  46969. // Vector2
  46970. serializationObject.vectors2 = {};
  46971. for (name in this._vectors2) {
  46972. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  46973. }
  46974. // Vector3
  46975. serializationObject.vectors3 = {};
  46976. for (name in this._vectors3) {
  46977. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  46978. }
  46979. // Vector4
  46980. serializationObject.vectors4 = {};
  46981. for (name in this._vectors4) {
  46982. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  46983. }
  46984. // Matrix
  46985. serializationObject.matrices = {};
  46986. for (name in this._matrices) {
  46987. serializationObject.matrices[name] = this._matrices[name].asArray();
  46988. }
  46989. // Matrix 3x3
  46990. serializationObject.matrices3x3 = {};
  46991. for (name in this._matrices3x3) {
  46992. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  46993. }
  46994. // Matrix 2x2
  46995. serializationObject.matrices2x2 = {};
  46996. for (name in this._matrices2x2) {
  46997. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  46998. }
  46999. // Vector3Array
  47000. serializationObject.vectors3Arrays = {};
  47001. for (name in this._vectors3Arrays) {
  47002. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  47003. }
  47004. return serializationObject;
  47005. };
  47006. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  47007. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  47008. var name;
  47009. // Texture
  47010. for (name in source.textures) {
  47011. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  47012. }
  47013. // Texture arrays
  47014. for (name in source.textureArrays) {
  47015. var array = source.textureArrays[name];
  47016. var textureArray = new Array();
  47017. for (var index = 0; index < array.length; index++) {
  47018. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  47019. }
  47020. material.setTextureArray(name, textureArray);
  47021. }
  47022. // Float
  47023. for (name in source.floats) {
  47024. material.setFloat(name, source.floats[name]);
  47025. }
  47026. // Float s
  47027. for (name in source.floatsArrays) {
  47028. material.setFloats(name, source.floatsArrays[name]);
  47029. }
  47030. // Color3
  47031. for (name in source.colors3) {
  47032. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  47033. }
  47034. // Color3 arrays
  47035. for (name in source.colors3Arrays) {
  47036. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  47037. if (i % 3 === 0) {
  47038. arr.push([num]);
  47039. }
  47040. else {
  47041. arr[arr.length - 1].push(num);
  47042. }
  47043. return arr;
  47044. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  47045. material.setColor3Array(name, colors);
  47046. }
  47047. // Color4
  47048. for (name in source.colors4) {
  47049. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  47050. }
  47051. // Vector2
  47052. for (name in source.vectors2) {
  47053. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  47054. }
  47055. // Vector3
  47056. for (name in source.vectors3) {
  47057. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  47058. }
  47059. // Vector4
  47060. for (name in source.vectors4) {
  47061. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  47062. }
  47063. // Matrix
  47064. for (name in source.matrices) {
  47065. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  47066. }
  47067. // Matrix 3x3
  47068. for (name in source.matrices3x3) {
  47069. material.setMatrix3x3(name, source.matrices3x3[name]);
  47070. }
  47071. // Matrix 2x2
  47072. for (name in source.matrices2x2) {
  47073. material.setMatrix2x2(name, source.matrices2x2[name]);
  47074. }
  47075. // Vector3Array
  47076. for (name in source.vectors3Arrays) {
  47077. material.setArray3(name, source.vectors3Arrays[name]);
  47078. }
  47079. return material;
  47080. };
  47081. return ShaderMaterial;
  47082. }(BABYLON.Material));
  47083. BABYLON.ShaderMaterial = ShaderMaterial;
  47084. })(BABYLON || (BABYLON = {}));
  47085. //# sourceMappingURL=babylon.shaderMaterial.js.map
  47086. var BABYLON;
  47087. (function (BABYLON) {
  47088. var MeshBuilder = /** @class */ (function () {
  47089. function MeshBuilder() {
  47090. }
  47091. MeshBuilder.updateSideOrientation = function (orientation) {
  47092. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  47093. return BABYLON.Mesh.DOUBLESIDE;
  47094. }
  47095. if (orientation === undefined || orientation === null) {
  47096. return BABYLON.Mesh.FRONTSIDE;
  47097. }
  47098. return orientation;
  47099. };
  47100. /**
  47101. * Creates a box mesh.
  47102. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  47103. * The parameter `size` sets the size (float) of each box side (default 1).
  47104. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  47105. * 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).
  47106. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47107. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47108. * 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).
  47109. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47110. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47111. */
  47112. MeshBuilder.CreateBox = function (name, options, scene) {
  47113. if (scene === void 0) { scene = null; }
  47114. var box = new BABYLON.Mesh(name, scene);
  47115. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47116. box._originalBuilderSideOrientation = options.sideOrientation;
  47117. var vertexData = BABYLON.VertexData.CreateBox(options);
  47118. vertexData.applyToMesh(box, options.updatable);
  47119. return box;
  47120. };
  47121. /**
  47122. * Creates a sphere mesh.
  47123. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  47124. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  47125. * 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`).
  47126. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  47127. * 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
  47128. * 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).
  47129. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47130. * 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).
  47131. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47133. */
  47134. MeshBuilder.CreateSphere = function (name, options, scene) {
  47135. var sphere = new BABYLON.Mesh(name, scene);
  47136. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47137. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47138. var vertexData = BABYLON.VertexData.CreateSphere(options);
  47139. vertexData.applyToMesh(sphere, options.updatable);
  47140. return sphere;
  47141. };
  47142. /**
  47143. * Creates a plane polygonal mesh. By default, this is a disc.
  47144. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  47145. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  47146. * 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.
  47147. * 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
  47148. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47149. * 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).
  47150. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47151. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47152. */
  47153. MeshBuilder.CreateDisc = function (name, options, scene) {
  47154. if (scene === void 0) { scene = null; }
  47155. var disc = new BABYLON.Mesh(name, scene);
  47156. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47157. disc._originalBuilderSideOrientation = options.sideOrientation;
  47158. var vertexData = BABYLON.VertexData.CreateDisc(options);
  47159. vertexData.applyToMesh(disc, options.updatable);
  47160. return disc;
  47161. };
  47162. /**
  47163. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  47164. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  47165. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  47166. * 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`).
  47167. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  47168. * 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.
  47169. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47170. * 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).
  47171. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47173. */
  47174. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  47175. var sphere = new BABYLON.Mesh(name, scene);
  47176. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47177. sphere._originalBuilderSideOrientation = options.sideOrientation;
  47178. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  47179. vertexData.applyToMesh(sphere, options.updatable);
  47180. return sphere;
  47181. };
  47182. ;
  47183. /**
  47184. * Creates a ribbon mesh.
  47185. * 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.
  47186. *
  47187. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  47188. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  47189. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  47190. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  47191. * 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.
  47192. * 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.
  47193. * 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
  47194. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47195. * 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).
  47196. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47197. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47198. * 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.
  47199. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  47200. * 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
  47201. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  47202. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  47203. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47204. */
  47205. MeshBuilder.CreateRibbon = function (name, options, scene) {
  47206. if (scene === void 0) { scene = null; }
  47207. var pathArray = options.pathArray;
  47208. var closeArray = options.closeArray;
  47209. var closePath = options.closePath;
  47210. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47211. var instance = options.instance;
  47212. var updatable = options.updatable;
  47213. if (instance) {
  47214. // positionFunction : ribbon case
  47215. // only pathArray and sideOrientation parameters are taken into account for positions update
  47216. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  47217. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  47218. var positionFunction = function (positions) {
  47219. var minlg = pathArray[0].length;
  47220. var i = 0;
  47221. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  47222. for (var si = 1; si <= ns; si++) {
  47223. for (var p = 0; p < pathArray.length; p++) {
  47224. var path = pathArray[p];
  47225. var l = path.length;
  47226. minlg = (minlg < l) ? minlg : l;
  47227. var j = 0;
  47228. while (j < minlg) {
  47229. positions[i] = path[j].x;
  47230. positions[i + 1] = path[j].y;
  47231. positions[i + 2] = path[j].z;
  47232. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  47233. BABYLON.Tmp.Vector3[0].x = path[j].x;
  47234. }
  47235. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  47236. BABYLON.Tmp.Vector3[1].x = path[j].x;
  47237. }
  47238. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  47239. BABYLON.Tmp.Vector3[0].y = path[j].y;
  47240. }
  47241. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  47242. BABYLON.Tmp.Vector3[1].y = path[j].y;
  47243. }
  47244. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  47245. BABYLON.Tmp.Vector3[0].z = path[j].z;
  47246. }
  47247. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  47248. BABYLON.Tmp.Vector3[1].z = path[j].z;
  47249. }
  47250. j++;
  47251. i += 3;
  47252. }
  47253. if (instance._closePath) {
  47254. positions[i] = path[0].x;
  47255. positions[i + 1] = path[0].y;
  47256. positions[i + 2] = path[0].z;
  47257. i += 3;
  47258. }
  47259. }
  47260. }
  47261. };
  47262. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47263. positionFunction(positions);
  47264. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  47265. instance._boundingInfo.update(instance._worldMatrix);
  47266. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  47267. if (options.colors) {
  47268. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47269. for (var c = 0; c < options.colors.length; c++) {
  47270. colors[c * 4] = options.colors[c].r;
  47271. colors[c * 4 + 1] = options.colors[c].g;
  47272. colors[c * 4 + 2] = options.colors[c].b;
  47273. colors[c * 4 + 3] = options.colors[c].a;
  47274. }
  47275. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  47276. }
  47277. if (options.uvs) {
  47278. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47279. for (var i = 0; i < options.uvs.length; i++) {
  47280. uvs[i * 2] = options.uvs[i].x;
  47281. uvs[i * 2 + 1] = options.uvs[i].y;
  47282. }
  47283. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  47284. }
  47285. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  47286. var indices = instance.getIndices();
  47287. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47288. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  47289. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  47290. if (instance._closePath) {
  47291. var indexFirst = 0;
  47292. var indexLast = 0;
  47293. for (var p = 0; p < pathArray.length; p++) {
  47294. indexFirst = instance._idx[p] * 3;
  47295. if (p + 1 < pathArray.length) {
  47296. indexLast = (instance._idx[p + 1] - 1) * 3;
  47297. }
  47298. else {
  47299. indexLast = normals.length - 3;
  47300. }
  47301. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  47302. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  47303. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  47304. normals[indexLast] = normals[indexFirst];
  47305. normals[indexLast + 1] = normals[indexFirst + 1];
  47306. normals[indexLast + 2] = normals[indexFirst + 2];
  47307. }
  47308. }
  47309. if (!(instance.areNormalsFrozen)) {
  47310. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  47311. }
  47312. }
  47313. return instance;
  47314. }
  47315. else {
  47316. var ribbon = new BABYLON.Mesh(name, scene);
  47317. ribbon._originalBuilderSideOrientation = sideOrientation;
  47318. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  47319. if (closePath) {
  47320. ribbon._idx = vertexData._idx;
  47321. }
  47322. ribbon._closePath = closePath;
  47323. ribbon._closeArray = closeArray;
  47324. vertexData.applyToMesh(ribbon, updatable);
  47325. return ribbon;
  47326. }
  47327. };
  47328. /**
  47329. * Creates a cylinder or a cone mesh.
  47330. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  47331. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  47332. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  47333. * 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.
  47334. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  47335. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  47336. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  47337. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  47338. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  47339. * 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).
  47340. * 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
  47341. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  47342. * 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
  47343. * 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.
  47344. * If `enclose` is false, a ring surface is one element.
  47345. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  47346. * 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
  47347. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47348. * 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).
  47349. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47350. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47351. */
  47352. MeshBuilder.CreateCylinder = function (name, options, scene) {
  47353. var cylinder = new BABYLON.Mesh(name, scene);
  47354. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47355. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  47356. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  47357. vertexData.applyToMesh(cylinder, options.updatable);
  47358. return cylinder;
  47359. };
  47360. /**
  47361. * Creates a torus mesh.
  47362. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  47363. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  47364. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  47365. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  47366. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47367. * 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).
  47368. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47369. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47370. */
  47371. MeshBuilder.CreateTorus = function (name, options, scene) {
  47372. var torus = new BABYLON.Mesh(name, scene);
  47373. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47374. torus._originalBuilderSideOrientation = options.sideOrientation;
  47375. var vertexData = BABYLON.VertexData.CreateTorus(options);
  47376. vertexData.applyToMesh(torus, options.updatable);
  47377. return torus;
  47378. };
  47379. /**
  47380. * Creates a torus knot mesh.
  47381. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  47382. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  47383. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  47384. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  47385. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  47386. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47387. * 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).
  47388. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47389. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47390. */
  47391. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  47392. var torusKnot = new BABYLON.Mesh(name, scene);
  47393. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47394. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  47395. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  47396. vertexData.applyToMesh(torusKnot, options.updatable);
  47397. return torusKnot;
  47398. };
  47399. /**
  47400. * Creates a line system mesh.
  47401. * A line system is a pool of many lines gathered in a single mesh.
  47402. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  47403. * 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.
  47404. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  47405. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  47406. * 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
  47407. * 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
  47408. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  47409. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47410. */
  47411. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  47412. var instance = options.instance;
  47413. var lines = options.lines;
  47414. if (instance) {
  47415. var positionFunction = function (positions) {
  47416. var i = 0;
  47417. for (var l = 0; l < lines.length; l++) {
  47418. var points = lines[l];
  47419. for (var p = 0; p < points.length; p++) {
  47420. positions[i] = points[p].x;
  47421. positions[i + 1] = points[p].y;
  47422. positions[i + 2] = points[p].z;
  47423. i += 3;
  47424. }
  47425. }
  47426. };
  47427. instance.updateMeshPositions(positionFunction, false);
  47428. return instance;
  47429. }
  47430. // line system creation
  47431. var lineSystem = new BABYLON.LinesMesh(name, scene);
  47432. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  47433. vertexData.applyToMesh(lineSystem, options.updatable);
  47434. return lineSystem;
  47435. };
  47436. /**
  47437. * Creates a line mesh.
  47438. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  47439. * 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.
  47440. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47441. * The parameter `points` is an array successive Vector3.
  47442. * 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
  47443. * When updating an instance, remember that only point positions can change, not the number of points.
  47444. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47445. */
  47446. MeshBuilder.CreateLines = function (name, options, scene) {
  47447. if (scene === void 0) { scene = null; }
  47448. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  47449. return lines;
  47450. };
  47451. /**
  47452. * Creates a dashed line mesh.
  47453. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  47454. * 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.
  47455. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  47456. * The parameter `points` is an array successive Vector3.
  47457. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  47458. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  47459. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  47460. * 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
  47461. * When updating an instance, remember that only point positions can change, not the number of points.
  47462. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47463. */
  47464. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  47465. if (scene === void 0) { scene = null; }
  47466. var points = options.points;
  47467. var instance = options.instance;
  47468. var gapSize = options.gapSize || 1;
  47469. var dashSize = options.dashSize || 3;
  47470. if (instance) {
  47471. var positionFunction = function (positions) {
  47472. var curvect = BABYLON.Vector3.Zero();
  47473. var nbSeg = positions.length / 6;
  47474. var lg = 0;
  47475. var nb = 0;
  47476. var shft = 0;
  47477. var dashshft = 0;
  47478. var curshft = 0;
  47479. var p = 0;
  47480. var i = 0;
  47481. var j = 0;
  47482. for (i = 0; i < points.length - 1; i++) {
  47483. points[i + 1].subtractToRef(points[i], curvect);
  47484. lg += curvect.length();
  47485. }
  47486. shft = lg / nbSeg;
  47487. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  47488. for (i = 0; i < points.length - 1; i++) {
  47489. points[i + 1].subtractToRef(points[i], curvect);
  47490. nb = Math.floor(curvect.length() / shft);
  47491. curvect.normalize();
  47492. j = 0;
  47493. while (j < nb && p < positions.length) {
  47494. curshft = shft * j;
  47495. positions[p] = points[i].x + curshft * curvect.x;
  47496. positions[p + 1] = points[i].y + curshft * curvect.y;
  47497. positions[p + 2] = points[i].z + curshft * curvect.z;
  47498. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  47499. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  47500. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  47501. p += 6;
  47502. j++;
  47503. }
  47504. }
  47505. while (p < positions.length) {
  47506. positions[p] = points[i].x;
  47507. positions[p + 1] = points[i].y;
  47508. positions[p + 2] = points[i].z;
  47509. p += 3;
  47510. }
  47511. };
  47512. instance.updateMeshPositions(positionFunction, false);
  47513. return instance;
  47514. }
  47515. // dashed lines creation
  47516. var dashedLines = new BABYLON.LinesMesh(name, scene);
  47517. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  47518. vertexData.applyToMesh(dashedLines, options.updatable);
  47519. dashedLines.dashSize = dashSize;
  47520. dashedLines.gapSize = gapSize;
  47521. return dashedLines;
  47522. };
  47523. /**
  47524. * Creates an extruded shape mesh.
  47525. * 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.
  47526. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  47527. *
  47528. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47529. * 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
  47530. * extruded along the Z axis.
  47531. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47532. * 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.
  47533. * The parameter `scale` (float, default 1) is the value to scale the shape.
  47534. * 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
  47535. * 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
  47536. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47537. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47538. * 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).
  47539. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47540. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47541. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47542. */
  47543. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  47544. if (scene === void 0) { scene = null; }
  47545. var path = options.path;
  47546. var shape = options.shape;
  47547. var scale = options.scale || 1;
  47548. var rotation = options.rotation || 0;
  47549. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47550. var updatable = options.updatable;
  47551. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47552. var instance = options.instance || null;
  47553. var invertUV = options.invertUV || false;
  47554. 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);
  47555. };
  47556. /**
  47557. * Creates an custom extruded shape mesh.
  47558. * 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.
  47559. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  47560. *
  47561. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  47562. * 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
  47563. * extruded along the Z axis.
  47564. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  47565. * 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
  47566. * and the distance of this point from the begining of the path :
  47567. * ```javascript
  47568. * var rotationFunction = function(i, distance) {
  47569. * // do things
  47570. * return rotationValue; }
  47571. * ```
  47572. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  47573. * 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
  47574. * and the distance of this point from the begining of the path :
  47575. * ```javascript
  47576. * var scaleFunction = function(i, distance) {
  47577. * // do things
  47578. * return scaleValue;}
  47579. * ```
  47580. * It must returns a float value that will be the scale value applied to the shape on each path point.
  47581. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  47582. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  47583. * 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
  47584. * 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
  47585. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  47586. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47587. * 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).
  47588. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47589. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47590. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47591. */
  47592. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  47593. var path = options.path;
  47594. var shape = options.shape;
  47595. var scaleFunction = options.scaleFunction || (function () { return 1; });
  47596. var rotationFunction = options.rotationFunction || (function () { return 0; });
  47597. var ribbonCloseArray = options.ribbonCloseArray || false;
  47598. var ribbonClosePath = options.ribbonClosePath || false;
  47599. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  47600. var updatable = options.updatable;
  47601. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47602. var instance = options.instance;
  47603. var invertUV = options.invertUV || false;
  47604. 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);
  47605. };
  47606. /**
  47607. * Creates lathe mesh.
  47608. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  47609. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  47610. *
  47611. * 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
  47612. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  47613. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  47614. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  47615. * 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.
  47616. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  47617. * 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
  47618. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47619. * 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).
  47620. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47621. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47622. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47623. */
  47624. MeshBuilder.CreateLathe = function (name, options, scene) {
  47625. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  47626. var closed = (options.closed === undefined) ? true : options.closed;
  47627. var shape = options.shape;
  47628. var radius = options.radius || 1;
  47629. var tessellation = options.tessellation || 64;
  47630. var updatable = options.updatable;
  47631. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47632. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47633. var pi2 = Math.PI * 2;
  47634. var paths = new Array();
  47635. var invertUV = options.invertUV || false;
  47636. var i = 0;
  47637. var p = 0;
  47638. var step = pi2 / tessellation * arc;
  47639. var rotated;
  47640. var path = new Array();
  47641. ;
  47642. for (i = 0; i <= tessellation; i++) {
  47643. var path = [];
  47644. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  47645. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  47646. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  47647. }
  47648. for (p = 0; p < shape.length; p++) {
  47649. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  47650. path.push(rotated);
  47651. }
  47652. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  47653. 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));
  47654. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  47655. }
  47656. paths.push(path);
  47657. }
  47658. // lathe ribbon
  47659. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47660. return lathe;
  47661. };
  47662. /**
  47663. * Creates a plane mesh.
  47664. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47665. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  47666. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  47667. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  47668. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47669. * 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).
  47670. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47672. */
  47673. MeshBuilder.CreatePlane = function (name, options, scene) {
  47674. var plane = new BABYLON.Mesh(name, scene);
  47675. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47676. plane._originalBuilderSideOrientation = options.sideOrientation;
  47677. var vertexData = BABYLON.VertexData.CreatePlane(options);
  47678. vertexData.applyToMesh(plane, options.updatable);
  47679. if (options.sourcePlane) {
  47680. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  47681. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  47682. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  47683. plane.rotate(vectorProduct, product);
  47684. }
  47685. return plane;
  47686. };
  47687. /**
  47688. * Creates a ground mesh.
  47689. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  47690. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  47691. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  47692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47693. */
  47694. MeshBuilder.CreateGround = function (name, options, scene) {
  47695. var ground = new BABYLON.GroundMesh(name, scene);
  47696. ground._setReady(false);
  47697. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  47698. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  47699. ground._width = options.width || 1;
  47700. ground._height = options.height || 1;
  47701. ground._maxX = ground._width / 2;
  47702. ground._maxZ = ground._height / 2;
  47703. ground._minX = -ground._maxX;
  47704. ground._minZ = -ground._maxZ;
  47705. var vertexData = BABYLON.VertexData.CreateGround(options);
  47706. vertexData.applyToMesh(ground, options.updatable);
  47707. ground._setReady(true);
  47708. return ground;
  47709. };
  47710. /**
  47711. * Creates a tiled ground mesh.
  47712. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  47713. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  47714. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  47715. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  47716. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  47717. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  47718. * numbers of subdivisions on the ground width and height of each tile.
  47719. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47720. */
  47721. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  47722. var tiledGround = new BABYLON.Mesh(name, scene);
  47723. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  47724. vertexData.applyToMesh(tiledGround, options.updatable);
  47725. return tiledGround;
  47726. };
  47727. /**
  47728. * Creates a ground mesh from a height map.
  47729. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  47730. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  47731. * The parameter `url` sets the URL of the height map image resource.
  47732. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  47733. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  47734. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  47735. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  47736. * 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.
  47737. * 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).
  47738. * This function is passed the newly built mesh :
  47739. * ```javascript
  47740. * function(mesh) { // do things
  47741. * return; }
  47742. * ```
  47743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47744. */
  47745. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  47746. var width = options.width || 10.0;
  47747. var height = options.height || 10.0;
  47748. var subdivisions = options.subdivisions || 1 | 0;
  47749. var minHeight = options.minHeight || 0.0;
  47750. var maxHeight = options.maxHeight || 1.0;
  47751. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  47752. var updatable = options.updatable;
  47753. var onReady = options.onReady;
  47754. var ground = new BABYLON.GroundMesh(name, scene);
  47755. ground._subdivisionsX = subdivisions;
  47756. ground._subdivisionsY = subdivisions;
  47757. ground._width = width;
  47758. ground._height = height;
  47759. ground._maxX = ground._width / 2.0;
  47760. ground._maxZ = ground._height / 2.0;
  47761. ground._minX = -ground._maxX;
  47762. ground._minZ = -ground._maxZ;
  47763. ground._setReady(false);
  47764. var onload = function (img) {
  47765. // Getting height map data
  47766. var canvas = document.createElement("canvas");
  47767. var context = canvas.getContext("2d");
  47768. if (!context) {
  47769. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  47770. }
  47771. var bufferWidth = img.width;
  47772. var bufferHeight = img.height;
  47773. canvas.width = bufferWidth;
  47774. canvas.height = bufferHeight;
  47775. context.drawImage(img, 0, 0);
  47776. // Create VertexData from map data
  47777. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  47778. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  47779. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  47780. width: width, height: height,
  47781. subdivisions: subdivisions,
  47782. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  47783. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  47784. });
  47785. vertexData.applyToMesh(ground, updatable);
  47786. ground._setReady(true);
  47787. //execute ready callback, if set
  47788. if (onReady) {
  47789. onReady(ground);
  47790. }
  47791. };
  47792. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  47793. return ground;
  47794. };
  47795. /**
  47796. * Creates a polygon mesh.
  47797. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  47798. * 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.
  47799. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47800. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47801. * 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).
  47802. * Remember you can only change the shape positions, not their number when updating a polygon.
  47803. */
  47804. MeshBuilder.CreatePolygon = function (name, options, scene) {
  47805. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47806. var shape = options.shape;
  47807. var holes = options.holes || [];
  47808. var depth = options.depth || 0;
  47809. var contours = [];
  47810. var hole = [];
  47811. for (var i = 0; i < shape.length; i++) {
  47812. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  47813. }
  47814. var epsilon = 0.00000001;
  47815. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  47816. contours.pop();
  47817. }
  47818. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  47819. for (var hNb = 0; hNb < holes.length; hNb++) {
  47820. hole = [];
  47821. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  47822. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  47823. }
  47824. polygonTriangulation.addHole(hole);
  47825. }
  47826. var polygon = polygonTriangulation.build(options.updatable, depth);
  47827. polygon._originalBuilderSideOrientation = options.sideOrientation;
  47828. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  47829. vertexData.applyToMesh(polygon, options.updatable);
  47830. return polygon;
  47831. };
  47832. ;
  47833. /**
  47834. * Creates an extruded polygon mesh, with depth in the Y direction.
  47835. * 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).
  47836. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  47837. */
  47838. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  47839. return MeshBuilder.CreatePolygon(name, options, scene);
  47840. };
  47841. ;
  47842. /**
  47843. * Creates a tube mesh.
  47844. * 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.
  47845. *
  47846. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  47847. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  47848. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  47849. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  47850. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  47851. * 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.
  47852. * It must return a radius value (positive float) :
  47853. * ```javascript
  47854. * var radiusFunction = function(i, distance) {
  47855. * // do things
  47856. * return radius; }
  47857. * ```
  47858. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  47859. * 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
  47860. * 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
  47861. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47862. * 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).
  47863. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47864. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  47865. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47866. */
  47867. MeshBuilder.CreateTube = function (name, options, scene) {
  47868. var path = options.path;
  47869. var instance = options.instance;
  47870. var radius = 1.0;
  47871. if (instance) {
  47872. radius = instance.radius;
  47873. }
  47874. if (options.radius !== undefined) {
  47875. radius = options.radius;
  47876. }
  47877. ;
  47878. var tessellation = options.tessellation || 64 | 0;
  47879. var radiusFunction = options.radiusFunction || null;
  47880. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  47881. var invertUV = options.invertUV || false;
  47882. var updatable = options.updatable;
  47883. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47884. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  47885. // tube geometry
  47886. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  47887. var tangents = path3D.getTangents();
  47888. var normals = path3D.getNormals();
  47889. var distances = path3D.getDistances();
  47890. var pi2 = Math.PI * 2;
  47891. var step = pi2 / tessellation * arc;
  47892. var returnRadius = function () { return radius; };
  47893. var radiusFunctionFinal = radiusFunction || returnRadius;
  47894. var circlePath;
  47895. var rad;
  47896. var normal;
  47897. var rotated;
  47898. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  47899. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  47900. for (var i = 0; i < path.length; i++) {
  47901. rad = radiusFunctionFinal(i, distances[i]); // current radius
  47902. circlePath = Array(); // current circle array
  47903. normal = normals[i]; // current normal
  47904. for (var t = 0; t < tessellation; t++) {
  47905. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  47906. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  47907. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  47908. rotated.scaleInPlace(rad).addInPlace(path[i]);
  47909. circlePath[t] = rotated;
  47910. }
  47911. circlePaths[index] = circlePath;
  47912. index++;
  47913. }
  47914. // cap
  47915. var capPath = function (nbPoints, pathIndex) {
  47916. var pointCap = Array();
  47917. for (var i = 0; i < nbPoints; i++) {
  47918. pointCap.push(path[pathIndex]);
  47919. }
  47920. return pointCap;
  47921. };
  47922. switch (cap) {
  47923. case BABYLON.Mesh.NO_CAP:
  47924. break;
  47925. case BABYLON.Mesh.CAP_START:
  47926. circlePaths[0] = capPath(tessellation, 0);
  47927. circlePaths[1] = circlePaths[2].slice(0);
  47928. break;
  47929. case BABYLON.Mesh.CAP_END:
  47930. circlePaths[index] = circlePaths[index - 1].slice(0);
  47931. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47932. break;
  47933. case BABYLON.Mesh.CAP_ALL:
  47934. circlePaths[0] = capPath(tessellation, 0);
  47935. circlePaths[1] = circlePaths[2].slice(0);
  47936. circlePaths[index] = circlePaths[index - 1].slice(0);
  47937. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  47938. break;
  47939. default:
  47940. break;
  47941. }
  47942. return circlePaths;
  47943. };
  47944. var path3D;
  47945. var pathArray;
  47946. if (instance) {
  47947. var arc = options.arc || instance.arc;
  47948. path3D = (instance.path3D).update(path);
  47949. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  47950. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  47951. instance.path3D = path3D;
  47952. instance.pathArray = pathArray;
  47953. instance.arc = arc;
  47954. instance.radius = radius;
  47955. return instance;
  47956. }
  47957. // tube creation
  47958. path3D = new BABYLON.Path3D(path);
  47959. var newPathArray = new Array();
  47960. cap = (cap < 0 || cap > 3) ? 0 : cap;
  47961. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  47962. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  47963. tube.pathArray = pathArray;
  47964. tube.path3D = path3D;
  47965. tube.tessellation = tessellation;
  47966. tube.cap = cap;
  47967. tube.arc = options.arc;
  47968. tube.radius = radius;
  47969. return tube;
  47970. };
  47971. /**
  47972. * Creates a polyhedron mesh.
  47973. *
  47974. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  47975. * 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
  47976. * to choose the wanted type.
  47977. * The parameter `size` (positive float, default 1) sets the polygon size.
  47978. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  47979. * 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`.
  47980. * 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
  47981. * 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)`).
  47982. * 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
  47983. * 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.
  47984. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  47985. * 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).
  47986. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  47987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  47988. */
  47989. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  47990. var polyhedron = new BABYLON.Mesh(name, scene);
  47991. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  47992. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  47993. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  47994. vertexData.applyToMesh(polyhedron, options.updatable);
  47995. return polyhedron;
  47996. };
  47997. /**
  47998. * Creates a decal mesh.
  47999. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  48000. * 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.
  48001. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  48002. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  48003. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  48004. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  48005. */
  48006. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  48007. var indices = sourceMesh.getIndices();
  48008. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48009. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48010. var position = options.position || BABYLON.Vector3.Zero();
  48011. var normal = options.normal || BABYLON.Vector3.Up();
  48012. var size = options.size || BABYLON.Vector3.One();
  48013. var angle = options.angle || 0;
  48014. // Getting correct rotation
  48015. if (!normal) {
  48016. var target = new BABYLON.Vector3(0, 0, 1);
  48017. var camera = sourceMesh.getScene().activeCamera;
  48018. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  48019. normal = camera.globalPosition.subtract(cameraWorldTarget);
  48020. }
  48021. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  48022. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  48023. var pitch = Math.atan2(normal.y, len);
  48024. // Matrix
  48025. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  48026. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  48027. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  48028. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  48029. var vertexData = new BABYLON.VertexData();
  48030. vertexData.indices = [];
  48031. vertexData.positions = [];
  48032. vertexData.normals = [];
  48033. vertexData.uvs = [];
  48034. var currentVertexDataIndex = 0;
  48035. var extractDecalVector3 = function (indexId) {
  48036. var result = new BABYLON.PositionNormalVertex();
  48037. if (!indices || !positions || !normals) {
  48038. return result;
  48039. }
  48040. var vertexId = indices[indexId];
  48041. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  48042. // Send vector to decal local world
  48043. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  48044. // Get normal
  48045. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  48046. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  48047. return result;
  48048. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  48049. var clip = function (vertices, axis) {
  48050. if (vertices.length === 0) {
  48051. return vertices;
  48052. }
  48053. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  48054. var clipVertices = function (v0, v1) {
  48055. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  48056. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  48057. };
  48058. var result = new Array();
  48059. for (var index = 0; index < vertices.length; index += 3) {
  48060. var v1Out;
  48061. var v2Out;
  48062. var v3Out;
  48063. var total = 0;
  48064. var nV1 = null;
  48065. var nV2 = null;
  48066. var nV3 = null;
  48067. var nV4 = null;
  48068. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  48069. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  48070. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  48071. v1Out = d1 > 0;
  48072. v2Out = d2 > 0;
  48073. v3Out = d3 > 0;
  48074. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  48075. switch (total) {
  48076. case 0:
  48077. result.push(vertices[index]);
  48078. result.push(vertices[index + 1]);
  48079. result.push(vertices[index + 2]);
  48080. break;
  48081. case 1:
  48082. if (v1Out) {
  48083. nV1 = vertices[index + 1];
  48084. nV2 = vertices[index + 2];
  48085. nV3 = clipVertices(vertices[index], nV1);
  48086. nV4 = clipVertices(vertices[index], nV2);
  48087. }
  48088. if (v2Out) {
  48089. nV1 = vertices[index];
  48090. nV2 = vertices[index + 2];
  48091. nV3 = clipVertices(vertices[index + 1], nV1);
  48092. nV4 = clipVertices(vertices[index + 1], nV2);
  48093. result.push(nV3);
  48094. result.push(nV2.clone());
  48095. result.push(nV1.clone());
  48096. result.push(nV2.clone());
  48097. result.push(nV3.clone());
  48098. result.push(nV4);
  48099. break;
  48100. }
  48101. if (v3Out) {
  48102. nV1 = vertices[index];
  48103. nV2 = vertices[index + 1];
  48104. nV3 = clipVertices(vertices[index + 2], nV1);
  48105. nV4 = clipVertices(vertices[index + 2], nV2);
  48106. }
  48107. if (nV1 && nV2 && nV3 && nV4) {
  48108. result.push(nV1.clone());
  48109. result.push(nV2.clone());
  48110. result.push(nV3);
  48111. result.push(nV4);
  48112. result.push(nV3.clone());
  48113. result.push(nV2.clone());
  48114. }
  48115. break;
  48116. case 2:
  48117. if (!v1Out) {
  48118. nV1 = vertices[index].clone();
  48119. nV2 = clipVertices(nV1, vertices[index + 1]);
  48120. nV3 = clipVertices(nV1, vertices[index + 2]);
  48121. result.push(nV1);
  48122. result.push(nV2);
  48123. result.push(nV3);
  48124. }
  48125. if (!v2Out) {
  48126. nV1 = vertices[index + 1].clone();
  48127. nV2 = clipVertices(nV1, vertices[index + 2]);
  48128. nV3 = clipVertices(nV1, vertices[index]);
  48129. result.push(nV1);
  48130. result.push(nV2);
  48131. result.push(nV3);
  48132. }
  48133. if (!v3Out) {
  48134. nV1 = vertices[index + 2].clone();
  48135. nV2 = clipVertices(nV1, vertices[index]);
  48136. nV3 = clipVertices(nV1, vertices[index + 1]);
  48137. result.push(nV1);
  48138. result.push(nV2);
  48139. result.push(nV3);
  48140. }
  48141. break;
  48142. case 3:
  48143. break;
  48144. }
  48145. }
  48146. return result;
  48147. };
  48148. for (var index = 0; index < indices.length; index += 3) {
  48149. var faceVertices = new Array();
  48150. faceVertices.push(extractDecalVector3(index));
  48151. faceVertices.push(extractDecalVector3(index + 1));
  48152. faceVertices.push(extractDecalVector3(index + 2));
  48153. // Clip
  48154. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  48155. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  48156. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  48157. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  48158. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  48159. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  48160. if (faceVertices.length === 0) {
  48161. continue;
  48162. }
  48163. // Add UVs and get back to world
  48164. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  48165. var vertex = faceVertices[vIndex];
  48166. //TODO check for Int32Array | Uint32Array | Uint16Array
  48167. vertexData.indices.push(currentVertexDataIndex);
  48168. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  48169. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  48170. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  48171. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  48172. currentVertexDataIndex++;
  48173. }
  48174. }
  48175. // Return mesh
  48176. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  48177. vertexData.applyToMesh(decal);
  48178. decal.position = position.clone();
  48179. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  48180. return decal;
  48181. };
  48182. // Privates
  48183. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  48184. // extrusion geometry
  48185. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  48186. var tangents = path3D.getTangents();
  48187. var normals = path3D.getNormals();
  48188. var binormals = path3D.getBinormals();
  48189. var distances = path3D.getDistances();
  48190. var angle = 0;
  48191. var returnScale = function () { return scale !== null ? scale : 1; };
  48192. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  48193. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  48194. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  48195. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  48196. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  48197. for (var i = 0; i < curve.length; i++) {
  48198. var shapePath = new Array();
  48199. var angleStep = rotate(i, distances[i]);
  48200. var scaleRatio = scl(i, distances[i]);
  48201. for (var p = 0; p < shape.length; p++) {
  48202. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  48203. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  48204. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  48205. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  48206. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  48207. shapePath[p] = rotated;
  48208. }
  48209. shapePaths[index] = shapePath;
  48210. angle += angleStep;
  48211. index++;
  48212. }
  48213. // cap
  48214. var capPath = function (shapePath) {
  48215. var pointCap = Array();
  48216. var barycenter = BABYLON.Vector3.Zero();
  48217. var i;
  48218. for (i = 0; i < shapePath.length; i++) {
  48219. barycenter.addInPlace(shapePath[i]);
  48220. }
  48221. barycenter.scaleInPlace(1.0 / shapePath.length);
  48222. for (i = 0; i < shapePath.length; i++) {
  48223. pointCap.push(barycenter);
  48224. }
  48225. return pointCap;
  48226. };
  48227. switch (cap) {
  48228. case BABYLON.Mesh.NO_CAP:
  48229. break;
  48230. case BABYLON.Mesh.CAP_START:
  48231. shapePaths[0] = capPath(shapePaths[2]);
  48232. shapePaths[1] = shapePaths[2];
  48233. break;
  48234. case BABYLON.Mesh.CAP_END:
  48235. shapePaths[index] = shapePaths[index - 1];
  48236. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48237. break;
  48238. case BABYLON.Mesh.CAP_ALL:
  48239. shapePaths[0] = capPath(shapePaths[2]);
  48240. shapePaths[1] = shapePaths[2];
  48241. shapePaths[index] = shapePaths[index - 1];
  48242. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  48243. break;
  48244. default:
  48245. break;
  48246. }
  48247. return shapePaths;
  48248. };
  48249. var path3D;
  48250. var pathArray;
  48251. if (instance) {
  48252. path3D = (instance.path3D).update(curve);
  48253. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  48254. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  48255. return instance;
  48256. }
  48257. // extruded shape creation
  48258. path3D = new BABYLON.Path3D(curve);
  48259. var newShapePaths = new Array();
  48260. cap = (cap < 0 || cap > 3) ? 0 : cap;
  48261. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  48262. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  48263. extrudedGeneric.pathArray = pathArray;
  48264. extrudedGeneric.path3D = path3D;
  48265. extrudedGeneric.cap = cap;
  48266. return extrudedGeneric;
  48267. };
  48268. return MeshBuilder;
  48269. }());
  48270. BABYLON.MeshBuilder = MeshBuilder;
  48271. })(BABYLON || (BABYLON = {}));
  48272. //# sourceMappingURL=babylon.meshBuilder.js.map
  48273. var BABYLON;
  48274. (function (BABYLON) {
  48275. var AudioEngine = /** @class */ (function () {
  48276. function AudioEngine() {
  48277. this._audioContext = null;
  48278. this._audioContextInitialized = false;
  48279. this.canUseWebAudio = false;
  48280. this.WarnedWebAudioUnsupported = false;
  48281. this.unlocked = false;
  48282. this.isMP3supported = false;
  48283. this.isOGGsupported = false;
  48284. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  48285. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  48286. this.canUseWebAudio = true;
  48287. }
  48288. var audioElem = document.createElement('audio');
  48289. try {
  48290. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  48291. this.isMP3supported = true;
  48292. }
  48293. }
  48294. catch (e) {
  48295. // protect error during capability check.
  48296. }
  48297. try {
  48298. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  48299. this.isOGGsupported = true;
  48300. }
  48301. }
  48302. catch (e) {
  48303. // protect error during capability check.
  48304. }
  48305. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  48306. this._unlockiOSaudio();
  48307. }
  48308. else {
  48309. this.unlocked = true;
  48310. }
  48311. }
  48312. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  48313. get: function () {
  48314. if (!this._audioContextInitialized) {
  48315. this._initializeAudioContext();
  48316. }
  48317. return this._audioContext;
  48318. },
  48319. enumerable: true,
  48320. configurable: true
  48321. });
  48322. AudioEngine.prototype._unlockiOSaudio = function () {
  48323. var _this = this;
  48324. var unlockaudio = function () {
  48325. if (!_this.audioContext) {
  48326. return;
  48327. }
  48328. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  48329. var source = _this.audioContext.createBufferSource();
  48330. source.buffer = buffer;
  48331. source.connect(_this.audioContext.destination);
  48332. source.start(0);
  48333. setTimeout(function () {
  48334. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  48335. _this.unlocked = true;
  48336. window.removeEventListener('touchend', unlockaudio, false);
  48337. if (_this.onAudioUnlocked) {
  48338. _this.onAudioUnlocked();
  48339. }
  48340. }
  48341. }, 0);
  48342. };
  48343. window.addEventListener('touchend', unlockaudio, false);
  48344. };
  48345. AudioEngine.prototype._initializeAudioContext = function () {
  48346. try {
  48347. if (this.canUseWebAudio) {
  48348. this._audioContext = new AudioContext();
  48349. // create a global volume gain node
  48350. this.masterGain = this._audioContext.createGain();
  48351. this.masterGain.gain.value = 1;
  48352. this.masterGain.connect(this._audioContext.destination);
  48353. this._audioContextInitialized = true;
  48354. }
  48355. }
  48356. catch (e) {
  48357. this.canUseWebAudio = false;
  48358. BABYLON.Tools.Error("Web Audio: " + e.message);
  48359. }
  48360. };
  48361. AudioEngine.prototype.dispose = function () {
  48362. if (this.canUseWebAudio && this._audioContextInitialized) {
  48363. if (this._connectedAnalyser && this._audioContext) {
  48364. this._connectedAnalyser.stopDebugCanvas();
  48365. this._connectedAnalyser.dispose();
  48366. this.masterGain.disconnect();
  48367. this.masterGain.connect(this._audioContext.destination);
  48368. this._connectedAnalyser = null;
  48369. }
  48370. this.masterGain.gain.value = 1;
  48371. }
  48372. this.WarnedWebAudioUnsupported = false;
  48373. };
  48374. AudioEngine.prototype.getGlobalVolume = function () {
  48375. if (this.canUseWebAudio && this._audioContextInitialized) {
  48376. return this.masterGain.gain.value;
  48377. }
  48378. else {
  48379. return -1;
  48380. }
  48381. };
  48382. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  48383. if (this.canUseWebAudio && this._audioContextInitialized) {
  48384. this.masterGain.gain.value = newVolume;
  48385. }
  48386. };
  48387. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  48388. if (this._connectedAnalyser) {
  48389. this._connectedAnalyser.stopDebugCanvas();
  48390. }
  48391. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  48392. this._connectedAnalyser = analyser;
  48393. this.masterGain.disconnect();
  48394. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  48395. }
  48396. };
  48397. return AudioEngine;
  48398. }());
  48399. BABYLON.AudioEngine = AudioEngine;
  48400. })(BABYLON || (BABYLON = {}));
  48401. //# sourceMappingURL=babylon.audioEngine.js.map
  48402. var BABYLON;
  48403. (function (BABYLON) {
  48404. var Sound = /** @class */ (function () {
  48405. /**
  48406. * Create a sound and attach it to a scene
  48407. * @param name Name of your sound
  48408. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  48409. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  48410. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  48411. */
  48412. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  48413. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  48414. var _this = this;
  48415. this.autoplay = false;
  48416. this.loop = false;
  48417. this.useCustomAttenuation = false;
  48418. this.spatialSound = false;
  48419. this.refDistance = 1;
  48420. this.rolloffFactor = 1;
  48421. this.maxDistance = 100;
  48422. this.distanceModel = "linear";
  48423. this._panningModel = "equalpower";
  48424. this._playbackRate = 1;
  48425. this._streaming = false;
  48426. this._startTime = 0;
  48427. this._startOffset = 0;
  48428. this._position = BABYLON.Vector3.Zero();
  48429. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  48430. this._volume = 1;
  48431. this._isLoaded = false;
  48432. this._isReadyToPlay = false;
  48433. this.isPlaying = false;
  48434. this.isPaused = false;
  48435. this._isDirectional = false;
  48436. // Used if you'd like to create a directional sound.
  48437. // If not set, the sound will be omnidirectional
  48438. this._coneInnerAngle = 360;
  48439. this._coneOuterAngle = 360;
  48440. this._coneOuterGain = 0;
  48441. this._isOutputConnected = false;
  48442. this._urlType = "Unknown";
  48443. this.name = name;
  48444. this._scene = scene;
  48445. this._readyToPlayCallback = readyToPlayCallback;
  48446. // Default custom attenuation function is a linear attenuation
  48447. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  48448. if (currentDistance < maxDistance) {
  48449. return currentVolume * (1 - currentDistance / maxDistance);
  48450. }
  48451. else {
  48452. return 0;
  48453. }
  48454. };
  48455. if (options) {
  48456. this.autoplay = options.autoplay || false;
  48457. this.loop = options.loop || false;
  48458. // if volume === 0, we need another way to check this option
  48459. if (options.volume !== undefined) {
  48460. this._volume = options.volume;
  48461. }
  48462. this.spatialSound = options.spatialSound || false;
  48463. this.maxDistance = options.maxDistance || 100;
  48464. this.useCustomAttenuation = options.useCustomAttenuation || false;
  48465. this.rolloffFactor = options.rolloffFactor || 1;
  48466. this.refDistance = options.refDistance || 1;
  48467. this.distanceModel = options.distanceModel || "linear";
  48468. this._playbackRate = options.playbackRate || 1;
  48469. this._streaming = options.streaming || false;
  48470. }
  48471. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48472. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  48473. this._soundGain.gain.value = this._volume;
  48474. this._inputAudioNode = this._soundGain;
  48475. this._ouputAudioNode = this._soundGain;
  48476. if (this.spatialSound) {
  48477. this._createSpatialParameters();
  48478. }
  48479. this._scene.mainSoundTrack.AddSound(this);
  48480. var validParameter = true;
  48481. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  48482. if (urlOrArrayBuffer) {
  48483. if (typeof (urlOrArrayBuffer) === "string")
  48484. this._urlType = "String";
  48485. if (Array.isArray(urlOrArrayBuffer))
  48486. this._urlType = "Array";
  48487. if (urlOrArrayBuffer instanceof ArrayBuffer)
  48488. this._urlType = "ArrayBuffer";
  48489. var urls = [];
  48490. var codecSupportedFound = false;
  48491. switch (this._urlType) {
  48492. case "ArrayBuffer":
  48493. if (urlOrArrayBuffer.byteLength > 0) {
  48494. codecSupportedFound = true;
  48495. this._soundLoaded(urlOrArrayBuffer);
  48496. }
  48497. break;
  48498. case "String":
  48499. urls.push(urlOrArrayBuffer);
  48500. case "Array":
  48501. if (urls.length === 0)
  48502. urls = urlOrArrayBuffer;
  48503. // If we found a supported format, we load it immediately and stop the loop
  48504. for (var i = 0; i < urls.length; i++) {
  48505. var url = urls[i];
  48506. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  48507. codecSupportedFound = true;
  48508. }
  48509. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  48510. codecSupportedFound = true;
  48511. }
  48512. if (url.indexOf(".wav", url.length - 4) !== -1) {
  48513. codecSupportedFound = true;
  48514. }
  48515. if (url.indexOf("blob:") !== -1) {
  48516. codecSupportedFound = true;
  48517. }
  48518. if (codecSupportedFound) {
  48519. // Loading sound using XHR2
  48520. if (!this._streaming) {
  48521. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, undefined, this._scene.database, true);
  48522. }
  48523. else {
  48524. this._htmlAudioElement = new Audio(url);
  48525. this._htmlAudioElement.controls = false;
  48526. this._htmlAudioElement.loop = this.loop;
  48527. this._htmlAudioElement.crossOrigin = "anonymous";
  48528. this._htmlAudioElement.preload = "auto";
  48529. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  48530. _this._isReadyToPlay = true;
  48531. if (_this.autoplay) {
  48532. _this.play();
  48533. }
  48534. if (_this._readyToPlayCallback) {
  48535. _this._readyToPlayCallback();
  48536. }
  48537. });
  48538. document.body.appendChild(this._htmlAudioElement);
  48539. }
  48540. break;
  48541. }
  48542. }
  48543. break;
  48544. default:
  48545. validParameter = false;
  48546. break;
  48547. }
  48548. if (!validParameter) {
  48549. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  48550. }
  48551. else {
  48552. if (!codecSupportedFound) {
  48553. this._isReadyToPlay = true;
  48554. // Simulating a ready to play event to avoid breaking code path
  48555. if (this._readyToPlayCallback) {
  48556. window.setTimeout(function () {
  48557. if (_this._readyToPlayCallback) {
  48558. _this._readyToPlayCallback();
  48559. }
  48560. }, 1000);
  48561. }
  48562. }
  48563. }
  48564. }
  48565. }
  48566. else {
  48567. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  48568. this._scene.mainSoundTrack.AddSound(this);
  48569. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  48570. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  48571. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  48572. }
  48573. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  48574. if (this._readyToPlayCallback) {
  48575. window.setTimeout(function () {
  48576. if (_this._readyToPlayCallback) {
  48577. _this._readyToPlayCallback();
  48578. }
  48579. }, 1000);
  48580. }
  48581. }
  48582. }
  48583. Sound.prototype.dispose = function () {
  48584. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  48585. if (this.isPlaying) {
  48586. this.stop();
  48587. }
  48588. this._isReadyToPlay = false;
  48589. if (this.soundTrackId === -1) {
  48590. this._scene.mainSoundTrack.RemoveSound(this);
  48591. }
  48592. else {
  48593. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  48594. }
  48595. if (this._soundGain) {
  48596. this._soundGain.disconnect();
  48597. this._soundGain = null;
  48598. }
  48599. if (this._soundPanner) {
  48600. this._soundPanner.disconnect();
  48601. this._soundPanner = null;
  48602. }
  48603. if (this._soundSource) {
  48604. this._soundSource.disconnect();
  48605. this._soundSource = null;
  48606. }
  48607. this._audioBuffer = null;
  48608. if (this._htmlAudioElement) {
  48609. this._htmlAudioElement.pause();
  48610. this._htmlAudioElement.src = "";
  48611. document.body.removeChild(this._htmlAudioElement);
  48612. }
  48613. if (this._connectedMesh && this._registerFunc) {
  48614. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48615. this._connectedMesh = null;
  48616. }
  48617. }
  48618. };
  48619. Sound.prototype.isReady = function () {
  48620. return this._isReadyToPlay;
  48621. };
  48622. Sound.prototype._soundLoaded = function (audioData) {
  48623. var _this = this;
  48624. this._isLoaded = true;
  48625. if (!BABYLON.Engine.audioEngine.audioContext) {
  48626. return;
  48627. }
  48628. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  48629. _this._audioBuffer = buffer;
  48630. _this._isReadyToPlay = true;
  48631. if (_this.autoplay) {
  48632. _this.play();
  48633. }
  48634. if (_this._readyToPlayCallback) {
  48635. _this._readyToPlayCallback();
  48636. }
  48637. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  48638. };
  48639. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  48640. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48641. this._audioBuffer = audioBuffer;
  48642. this._isReadyToPlay = true;
  48643. }
  48644. };
  48645. Sound.prototype.updateOptions = function (options) {
  48646. if (options) {
  48647. this.loop = options.loop || this.loop;
  48648. this.maxDistance = options.maxDistance || this.maxDistance;
  48649. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  48650. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  48651. this.refDistance = options.refDistance || this.refDistance;
  48652. this.distanceModel = options.distanceModel || this.distanceModel;
  48653. this._playbackRate = options.playbackRate || this._playbackRate;
  48654. this._updateSpatialParameters();
  48655. if (this.isPlaying) {
  48656. if (this._streaming) {
  48657. this._htmlAudioElement.playbackRate = this._playbackRate;
  48658. }
  48659. else {
  48660. if (this._soundSource) {
  48661. this._soundSource.playbackRate.value = this._playbackRate;
  48662. }
  48663. }
  48664. }
  48665. }
  48666. };
  48667. Sound.prototype._createSpatialParameters = function () {
  48668. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  48669. if (this._scene.headphone) {
  48670. this._panningModel = "HRTF";
  48671. }
  48672. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  48673. this._updateSpatialParameters();
  48674. this._soundPanner.connect(this._ouputAudioNode);
  48675. this._inputAudioNode = this._soundPanner;
  48676. }
  48677. };
  48678. Sound.prototype._updateSpatialParameters = function () {
  48679. if (this.spatialSound && this._soundPanner) {
  48680. if (this.useCustomAttenuation) {
  48681. // Tricks to disable in a way embedded Web Audio attenuation
  48682. this._soundPanner.distanceModel = "linear";
  48683. this._soundPanner.maxDistance = Number.MAX_VALUE;
  48684. this._soundPanner.refDistance = 1;
  48685. this._soundPanner.rolloffFactor = 1;
  48686. this._soundPanner.panningModel = this._panningModel;
  48687. }
  48688. else {
  48689. this._soundPanner.distanceModel = this.distanceModel;
  48690. this._soundPanner.maxDistance = this.maxDistance;
  48691. this._soundPanner.refDistance = this.refDistance;
  48692. this._soundPanner.rolloffFactor = this.rolloffFactor;
  48693. this._soundPanner.panningModel = this._panningModel;
  48694. }
  48695. }
  48696. };
  48697. Sound.prototype.switchPanningModelToHRTF = function () {
  48698. this._panningModel = "HRTF";
  48699. this._switchPanningModel();
  48700. };
  48701. Sound.prototype.switchPanningModelToEqualPower = function () {
  48702. this._panningModel = "equalpower";
  48703. this._switchPanningModel();
  48704. };
  48705. Sound.prototype._switchPanningModel = function () {
  48706. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48707. this._soundPanner.panningModel = this._panningModel;
  48708. }
  48709. };
  48710. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  48711. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48712. if (this._isOutputConnected) {
  48713. this._ouputAudioNode.disconnect();
  48714. }
  48715. this._ouputAudioNode.connect(soundTrackAudioNode);
  48716. this._isOutputConnected = true;
  48717. }
  48718. };
  48719. /**
  48720. * Transform this sound into a directional source
  48721. * @param coneInnerAngle Size of the inner cone in degree
  48722. * @param coneOuterAngle Size of the outer cone in degree
  48723. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  48724. */
  48725. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  48726. if (coneOuterAngle < coneInnerAngle) {
  48727. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  48728. return;
  48729. }
  48730. this._coneInnerAngle = coneInnerAngle;
  48731. this._coneOuterAngle = coneOuterAngle;
  48732. this._coneOuterGain = coneOuterGain;
  48733. this._isDirectional = true;
  48734. if (this.isPlaying && this.loop) {
  48735. this.stop();
  48736. this.play();
  48737. }
  48738. };
  48739. Sound.prototype.setPosition = function (newPosition) {
  48740. this._position = newPosition;
  48741. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  48742. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48743. }
  48744. };
  48745. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  48746. this._localDirection = newLocalDirection;
  48747. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  48748. this._updateDirection();
  48749. }
  48750. };
  48751. Sound.prototype._updateDirection = function () {
  48752. if (!this._connectedMesh || !this._soundPanner) {
  48753. return;
  48754. }
  48755. var mat = this._connectedMesh.getWorldMatrix();
  48756. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  48757. direction.normalize();
  48758. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  48759. };
  48760. Sound.prototype.updateDistanceFromListener = function () {
  48761. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  48762. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  48763. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  48764. }
  48765. };
  48766. Sound.prototype.setAttenuationFunction = function (callback) {
  48767. this._customAttenuationFunction = callback;
  48768. };
  48769. /**
  48770. * Play the sound
  48771. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  48772. * @param offset (optional) Start the sound setting it at a specific time
  48773. */
  48774. Sound.prototype.play = function (time, offset) {
  48775. var _this = this;
  48776. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  48777. try {
  48778. if (this._startOffset < 0) {
  48779. time = -this._startOffset;
  48780. this._startOffset = 0;
  48781. }
  48782. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48783. if (!this._soundSource || !this._streamingSource) {
  48784. if (this.spatialSound && this._soundPanner) {
  48785. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  48786. if (this._isDirectional) {
  48787. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  48788. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  48789. this._soundPanner.coneOuterGain = this._coneOuterGain;
  48790. if (this._connectedMesh) {
  48791. this._updateDirection();
  48792. }
  48793. else {
  48794. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  48795. }
  48796. }
  48797. }
  48798. }
  48799. if (this._streaming) {
  48800. if (!this._streamingSource) {
  48801. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  48802. this._htmlAudioElement.onended = function () { _this._onended(); };
  48803. this._htmlAudioElement.playbackRate = this._playbackRate;
  48804. }
  48805. this._streamingSource.disconnect();
  48806. this._streamingSource.connect(this._inputAudioNode);
  48807. this._htmlAudioElement.play();
  48808. }
  48809. else {
  48810. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  48811. this._soundSource.buffer = this._audioBuffer;
  48812. this._soundSource.connect(this._inputAudioNode);
  48813. this._soundSource.loop = this.loop;
  48814. this._soundSource.playbackRate.value = this._playbackRate;
  48815. this._soundSource.onended = function () { _this._onended(); };
  48816. if (this._soundSource.buffer) {
  48817. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  48818. }
  48819. }
  48820. this._startTime = startTime;
  48821. this.isPlaying = true;
  48822. this.isPaused = false;
  48823. }
  48824. catch (ex) {
  48825. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  48826. }
  48827. }
  48828. };
  48829. Sound.prototype._onended = function () {
  48830. this.isPlaying = false;
  48831. if (this.onended) {
  48832. this.onended();
  48833. }
  48834. };
  48835. /**
  48836. * Stop the sound
  48837. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  48838. */
  48839. Sound.prototype.stop = function (time) {
  48840. if (this.isPlaying) {
  48841. if (this._streaming) {
  48842. this._htmlAudioElement.pause();
  48843. // Test needed for Firefox or it will generate an Invalid State Error
  48844. if (this._htmlAudioElement.currentTime > 0) {
  48845. this._htmlAudioElement.currentTime = 0;
  48846. }
  48847. }
  48848. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  48849. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  48850. this._soundSource.stop(stopTime);
  48851. this._soundSource.onended = function () { };
  48852. if (!this.isPaused) {
  48853. this._startOffset = 0;
  48854. }
  48855. }
  48856. this.isPlaying = false;
  48857. }
  48858. };
  48859. Sound.prototype.pause = function () {
  48860. if (this.isPlaying) {
  48861. this.isPaused = true;
  48862. if (this._streaming) {
  48863. this._htmlAudioElement.pause();
  48864. }
  48865. else if (BABYLON.Engine.audioEngine.audioContext) {
  48866. this.stop(0);
  48867. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  48868. }
  48869. }
  48870. };
  48871. Sound.prototype.setVolume = function (newVolume, time) {
  48872. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  48873. if (time && BABYLON.Engine.audioEngine.audioContext) {
  48874. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  48875. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  48876. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  48877. }
  48878. else {
  48879. this._soundGain.gain.value = newVolume;
  48880. }
  48881. }
  48882. this._volume = newVolume;
  48883. };
  48884. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  48885. this._playbackRate = newPlaybackRate;
  48886. if (this.isPlaying) {
  48887. if (this._streaming) {
  48888. this._htmlAudioElement.playbackRate = this._playbackRate;
  48889. }
  48890. else if (this._soundSource) {
  48891. this._soundSource.playbackRate.value = this._playbackRate;
  48892. }
  48893. }
  48894. };
  48895. Sound.prototype.getVolume = function () {
  48896. return this._volume;
  48897. };
  48898. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  48899. var _this = this;
  48900. if (this._connectedMesh && this._registerFunc) {
  48901. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48902. this._registerFunc = null;
  48903. }
  48904. this._connectedMesh = meshToConnectTo;
  48905. if (!this.spatialSound) {
  48906. this.spatialSound = true;
  48907. this._createSpatialParameters();
  48908. if (this.isPlaying && this.loop) {
  48909. this.stop();
  48910. this.play();
  48911. }
  48912. }
  48913. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  48914. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  48915. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  48916. };
  48917. Sound.prototype.detachFromMesh = function () {
  48918. if (this._connectedMesh && this._registerFunc) {
  48919. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  48920. this._registerFunc = null;
  48921. this._connectedMesh = null;
  48922. }
  48923. };
  48924. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  48925. var boundingInfo = connectedMesh.getBoundingInfo();
  48926. if (!boundingInfo) {
  48927. return;
  48928. }
  48929. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  48930. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  48931. this._updateDirection();
  48932. }
  48933. };
  48934. Sound.prototype.clone = function () {
  48935. var _this = this;
  48936. if (!this._streaming) {
  48937. var setBufferAndRun = function () {
  48938. if (_this._isReadyToPlay) {
  48939. clonedSound._audioBuffer = _this.getAudioBuffer();
  48940. clonedSound._isReadyToPlay = true;
  48941. if (clonedSound.autoplay) {
  48942. clonedSound.play();
  48943. }
  48944. }
  48945. else {
  48946. window.setTimeout(setBufferAndRun, 300);
  48947. }
  48948. };
  48949. var currentOptions = {
  48950. autoplay: this.autoplay, loop: this.loop,
  48951. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  48952. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  48953. refDistance: this.refDistance, distanceModel: this.distanceModel
  48954. };
  48955. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  48956. if (this.useCustomAttenuation) {
  48957. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  48958. }
  48959. clonedSound.setPosition(this._position);
  48960. clonedSound.setPlaybackRate(this._playbackRate);
  48961. setBufferAndRun();
  48962. return clonedSound;
  48963. }
  48964. else {
  48965. return null;
  48966. }
  48967. };
  48968. Sound.prototype.getAudioBuffer = function () {
  48969. return this._audioBuffer;
  48970. };
  48971. Sound.prototype.serialize = function () {
  48972. var serializationObject = {
  48973. name: this.name,
  48974. url: this.name,
  48975. autoplay: this.autoplay,
  48976. loop: this.loop,
  48977. volume: this._volume,
  48978. spatialSound: this.spatialSound,
  48979. maxDistance: this.maxDistance,
  48980. rolloffFactor: this.rolloffFactor,
  48981. refDistance: this.refDistance,
  48982. distanceModel: this.distanceModel,
  48983. playbackRate: this._playbackRate,
  48984. panningModel: this._panningModel,
  48985. soundTrackId: this.soundTrackId
  48986. };
  48987. if (this.spatialSound) {
  48988. if (this._connectedMesh)
  48989. serializationObject.connectedMeshId = this._connectedMesh.id;
  48990. serializationObject.position = this._position.asArray();
  48991. serializationObject.refDistance = this.refDistance;
  48992. serializationObject.distanceModel = this.distanceModel;
  48993. serializationObject.isDirectional = this._isDirectional;
  48994. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  48995. serializationObject.coneInnerAngle = this._coneInnerAngle;
  48996. serializationObject.coneOuterAngle = this._coneOuterAngle;
  48997. serializationObject.coneOuterGain = this._coneOuterGain;
  48998. }
  48999. return serializationObject;
  49000. };
  49001. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  49002. var soundName = parsedSound.name;
  49003. var soundUrl;
  49004. if (parsedSound.url) {
  49005. soundUrl = rootUrl + parsedSound.url;
  49006. }
  49007. else {
  49008. soundUrl = rootUrl + soundName;
  49009. }
  49010. var options = {
  49011. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  49012. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  49013. rolloffFactor: parsedSound.rolloffFactor,
  49014. refDistance: parsedSound.refDistance,
  49015. distanceModel: parsedSound.distanceModel,
  49016. playbackRate: parsedSound.playbackRate
  49017. };
  49018. var newSound;
  49019. if (!sourceSound) {
  49020. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  49021. scene._addPendingData(newSound);
  49022. }
  49023. else {
  49024. var setBufferAndRun = function () {
  49025. if (sourceSound._isReadyToPlay) {
  49026. newSound._audioBuffer = sourceSound.getAudioBuffer();
  49027. newSound._isReadyToPlay = true;
  49028. if (newSound.autoplay) {
  49029. newSound.play();
  49030. }
  49031. }
  49032. else {
  49033. window.setTimeout(setBufferAndRun, 300);
  49034. }
  49035. };
  49036. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  49037. setBufferAndRun();
  49038. }
  49039. if (parsedSound.position) {
  49040. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  49041. newSound.setPosition(soundPosition);
  49042. }
  49043. if (parsedSound.isDirectional) {
  49044. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  49045. if (parsedSound.localDirectionToMesh) {
  49046. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  49047. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  49048. }
  49049. }
  49050. if (parsedSound.connectedMeshId) {
  49051. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  49052. if (connectedMesh) {
  49053. newSound.attachToMesh(connectedMesh);
  49054. }
  49055. }
  49056. return newSound;
  49057. };
  49058. return Sound;
  49059. }());
  49060. BABYLON.Sound = Sound;
  49061. })(BABYLON || (BABYLON = {}));
  49062. //# sourceMappingURL=babylon.sound.js.map
  49063. var BABYLON;
  49064. (function (BABYLON) {
  49065. var SoundTrack = /** @class */ (function () {
  49066. function SoundTrack(scene, options) {
  49067. this.id = -1;
  49068. this._isMainTrack = false;
  49069. this._isInitialized = false;
  49070. this._scene = scene;
  49071. this.soundCollection = new Array();
  49072. this._options = options;
  49073. if (!this._isMainTrack) {
  49074. this._scene.soundTracks.push(this);
  49075. this.id = this._scene.soundTracks.length - 1;
  49076. }
  49077. }
  49078. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  49079. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  49080. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  49081. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  49082. if (this._options) {
  49083. if (this._options.volume) {
  49084. this._outputAudioNode.gain.value = this._options.volume;
  49085. }
  49086. if (this._options.mainTrack) {
  49087. this._isMainTrack = this._options.mainTrack;
  49088. }
  49089. }
  49090. this._isInitialized = true;
  49091. }
  49092. };
  49093. SoundTrack.prototype.dispose = function () {
  49094. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49095. if (this._connectedAnalyser) {
  49096. this._connectedAnalyser.stopDebugCanvas();
  49097. }
  49098. while (this.soundCollection.length) {
  49099. this.soundCollection[0].dispose();
  49100. }
  49101. if (this._outputAudioNode) {
  49102. this._outputAudioNode.disconnect();
  49103. }
  49104. this._outputAudioNode = null;
  49105. }
  49106. };
  49107. SoundTrack.prototype.AddSound = function (sound) {
  49108. if (!this._isInitialized) {
  49109. this._initializeSoundTrackAudioGraph();
  49110. }
  49111. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49112. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  49113. }
  49114. if (sound.soundTrackId) {
  49115. if (sound.soundTrackId === -1) {
  49116. this._scene.mainSoundTrack.RemoveSound(sound);
  49117. }
  49118. else {
  49119. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  49120. }
  49121. }
  49122. this.soundCollection.push(sound);
  49123. sound.soundTrackId = this.id;
  49124. };
  49125. SoundTrack.prototype.RemoveSound = function (sound) {
  49126. var index = this.soundCollection.indexOf(sound);
  49127. if (index !== -1) {
  49128. this.soundCollection.splice(index, 1);
  49129. }
  49130. };
  49131. SoundTrack.prototype.setVolume = function (newVolume) {
  49132. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49133. this._outputAudioNode.gain.value = newVolume;
  49134. }
  49135. };
  49136. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  49137. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49138. for (var i = 0; i < this.soundCollection.length; i++) {
  49139. this.soundCollection[i].switchPanningModelToHRTF();
  49140. }
  49141. }
  49142. };
  49143. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  49144. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  49145. for (var i = 0; i < this.soundCollection.length; i++) {
  49146. this.soundCollection[i].switchPanningModelToEqualPower();
  49147. }
  49148. }
  49149. };
  49150. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  49151. if (this._connectedAnalyser) {
  49152. this._connectedAnalyser.stopDebugCanvas();
  49153. }
  49154. this._connectedAnalyser = analyser;
  49155. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  49156. this._outputAudioNode.disconnect();
  49157. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  49158. }
  49159. };
  49160. return SoundTrack;
  49161. }());
  49162. BABYLON.SoundTrack = SoundTrack;
  49163. })(BABYLON || (BABYLON = {}));
  49164. //# sourceMappingURL=babylon.soundtrack.js.map
  49165. var BABYLON;
  49166. (function (BABYLON) {
  49167. var Analyser = /** @class */ (function () {
  49168. function Analyser(scene) {
  49169. this.SMOOTHING = 0.75;
  49170. this.FFT_SIZE = 512;
  49171. this.BARGRAPHAMPLITUDE = 256;
  49172. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  49173. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  49174. this._scene = scene;
  49175. this._audioEngine = BABYLON.Engine.audioEngine;
  49176. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  49177. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  49178. this._webAudioAnalyser.minDecibels = -140;
  49179. this._webAudioAnalyser.maxDecibels = 0;
  49180. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49181. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  49182. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  49183. }
  49184. }
  49185. Analyser.prototype.getFrequencyBinCount = function () {
  49186. if (this._audioEngine.canUseWebAudio) {
  49187. return this._webAudioAnalyser.frequencyBinCount;
  49188. }
  49189. else {
  49190. return 0;
  49191. }
  49192. };
  49193. Analyser.prototype.getByteFrequencyData = function () {
  49194. if (this._audioEngine.canUseWebAudio) {
  49195. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49196. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49197. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  49198. }
  49199. return this._byteFreqs;
  49200. };
  49201. Analyser.prototype.getByteTimeDomainData = function () {
  49202. if (this._audioEngine.canUseWebAudio) {
  49203. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49204. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49205. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  49206. }
  49207. return this._byteTime;
  49208. };
  49209. Analyser.prototype.getFloatFrequencyData = function () {
  49210. if (this._audioEngine.canUseWebAudio) {
  49211. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  49212. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  49213. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  49214. }
  49215. return this._floatFreqs;
  49216. };
  49217. Analyser.prototype.drawDebugCanvas = function () {
  49218. var _this = this;
  49219. if (this._audioEngine.canUseWebAudio) {
  49220. if (!this._debugCanvas) {
  49221. this._debugCanvas = document.createElement("canvas");
  49222. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  49223. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  49224. this._debugCanvas.style.position = "absolute";
  49225. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  49226. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  49227. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  49228. document.body.appendChild(this._debugCanvas);
  49229. this._registerFunc = function () {
  49230. _this.drawDebugCanvas();
  49231. };
  49232. this._scene.registerBeforeRender(this._registerFunc);
  49233. }
  49234. if (this._registerFunc && this._debugCanvasContext) {
  49235. var workingArray = this.getByteFrequencyData();
  49236. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  49237. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  49238. // Draw the frequency domain chart.
  49239. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  49240. var value = workingArray[i];
  49241. var percent = value / this.BARGRAPHAMPLITUDE;
  49242. var height = this.DEBUGCANVASSIZE.height * percent;
  49243. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  49244. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  49245. var hue = i / this.getFrequencyBinCount() * 360;
  49246. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  49247. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  49248. }
  49249. }
  49250. }
  49251. };
  49252. Analyser.prototype.stopDebugCanvas = function () {
  49253. if (this._debugCanvas) {
  49254. if (this._registerFunc) {
  49255. this._scene.unregisterBeforeRender(this._registerFunc);
  49256. this._registerFunc = null;
  49257. }
  49258. document.body.removeChild(this._debugCanvas);
  49259. this._debugCanvas = null;
  49260. this._debugCanvasContext = null;
  49261. }
  49262. };
  49263. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  49264. if (this._audioEngine.canUseWebAudio) {
  49265. inputAudioNode.connect(this._webAudioAnalyser);
  49266. this._webAudioAnalyser.connect(outputAudioNode);
  49267. }
  49268. };
  49269. Analyser.prototype.dispose = function () {
  49270. if (this._audioEngine.canUseWebAudio) {
  49271. this._webAudioAnalyser.disconnect();
  49272. }
  49273. };
  49274. return Analyser;
  49275. }());
  49276. BABYLON.Analyser = Analyser;
  49277. })(BABYLON || (BABYLON = {}));
  49278. //# sourceMappingURL=babylon.analyser.js.map
  49279. var BABYLON;
  49280. (function (BABYLON) {
  49281. var CubeTexture = /** @class */ (function (_super) {
  49282. __extends(CubeTexture, _super);
  49283. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  49284. if (extensions === void 0) { extensions = null; }
  49285. if (noMipmap === void 0) { noMipmap = false; }
  49286. if (files === void 0) { files = null; }
  49287. if (onLoad === void 0) { onLoad = null; }
  49288. if (onError === void 0) { onError = null; }
  49289. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  49290. if (prefiltered === void 0) { prefiltered = false; }
  49291. if (forcedExtension === void 0) { forcedExtension = null; }
  49292. var _this = _super.call(this, scene) || this;
  49293. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49294. _this.name = rootUrl;
  49295. _this.url = rootUrl;
  49296. _this._noMipmap = noMipmap;
  49297. _this.hasAlpha = false;
  49298. _this._format = format;
  49299. _this._prefiltered = prefiltered;
  49300. _this.isCube = true;
  49301. _this._textureMatrix = BABYLON.Matrix.Identity();
  49302. if (prefiltered) {
  49303. _this.gammaSpace = false;
  49304. }
  49305. if (!rootUrl && !files) {
  49306. return _this;
  49307. }
  49308. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  49309. if (!files) {
  49310. if (!extensions) {
  49311. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  49312. }
  49313. files = [];
  49314. for (var index = 0; index < extensions.length; index++) {
  49315. files.push(rootUrl + extensions[index]);
  49316. }
  49317. _this._extensions = extensions;
  49318. }
  49319. _this._files = files;
  49320. if (!_this._texture) {
  49321. if (!scene.useDelayedTextureLoading) {
  49322. if (prefiltered) {
  49323. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  49324. }
  49325. else {
  49326. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  49327. }
  49328. }
  49329. else {
  49330. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  49331. }
  49332. }
  49333. else if (onLoad) {
  49334. if (_this._texture.isReady) {
  49335. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  49336. }
  49337. else {
  49338. _this._texture.onLoadedObservable.add(onLoad);
  49339. }
  49340. }
  49341. return _this;
  49342. }
  49343. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  49344. return new CubeTexture("", scene, null, noMipmap, files);
  49345. };
  49346. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  49347. if (forcedExtension === void 0) { forcedExtension = null; }
  49348. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  49349. };
  49350. // Methods
  49351. CubeTexture.prototype.delayLoad = function () {
  49352. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  49353. return;
  49354. }
  49355. var scene = this.getScene();
  49356. if (!scene) {
  49357. return;
  49358. }
  49359. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  49360. this._texture = this._getFromCache(this.url, this._noMipmap);
  49361. if (!this._texture) {
  49362. if (this._prefiltered) {
  49363. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  49364. }
  49365. else {
  49366. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  49367. }
  49368. }
  49369. };
  49370. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  49371. return this._textureMatrix;
  49372. };
  49373. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  49374. this._textureMatrix = value;
  49375. };
  49376. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  49377. var texture = BABYLON.SerializationHelper.Parse(function () {
  49378. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  49379. }, parsedTexture, scene);
  49380. // Animations
  49381. if (parsedTexture.animations) {
  49382. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  49383. var parsedAnimation = parsedTexture.animations[animationIndex];
  49384. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  49385. }
  49386. }
  49387. return texture;
  49388. };
  49389. CubeTexture.prototype.clone = function () {
  49390. var _this = this;
  49391. return BABYLON.SerializationHelper.Clone(function () {
  49392. var scene = _this.getScene();
  49393. if (!scene) {
  49394. return _this;
  49395. }
  49396. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  49397. }, this);
  49398. };
  49399. return CubeTexture;
  49400. }(BABYLON.BaseTexture));
  49401. BABYLON.CubeTexture = CubeTexture;
  49402. })(BABYLON || (BABYLON = {}));
  49403. //# sourceMappingURL=babylon.cubeTexture.js.map
  49404. var BABYLON;
  49405. (function (BABYLON) {
  49406. var RenderTargetTexture = /** @class */ (function (_super) {
  49407. __extends(RenderTargetTexture, _super);
  49408. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  49409. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  49410. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49411. if (isCube === void 0) { isCube = false; }
  49412. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49413. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  49414. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  49415. if (isMulti === void 0) { isMulti = false; }
  49416. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49417. _this.isCube = isCube;
  49418. /**
  49419. * Use this list to define the list of mesh you want to render.
  49420. */
  49421. _this.renderList = new Array();
  49422. _this.renderParticles = true;
  49423. _this.renderSprites = false;
  49424. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  49425. _this.ignoreCameraViewport = false;
  49426. // Events
  49427. /**
  49428. * An event triggered when the texture is unbind.
  49429. * @type {BABYLON.Observable}
  49430. */
  49431. _this.onBeforeBindObservable = new BABYLON.Observable();
  49432. /**
  49433. * An event triggered when the texture is unbind.
  49434. * @type {BABYLON.Observable}
  49435. */
  49436. _this.onAfterUnbindObservable = new BABYLON.Observable();
  49437. /**
  49438. * An event triggered before rendering the texture
  49439. * @type {BABYLON.Observable}
  49440. */
  49441. _this.onBeforeRenderObservable = new BABYLON.Observable();
  49442. /**
  49443. * An event triggered after rendering the texture
  49444. * @type {BABYLON.Observable}
  49445. */
  49446. _this.onAfterRenderObservable = new BABYLON.Observable();
  49447. /**
  49448. * An event triggered after the texture clear
  49449. * @type {BABYLON.Observable}
  49450. */
  49451. _this.onClearObservable = new BABYLON.Observable();
  49452. _this._currentRefreshId = -1;
  49453. _this._refreshRate = 1;
  49454. _this._samples = 1;
  49455. scene = _this.getScene();
  49456. if (!scene) {
  49457. return _this;
  49458. }
  49459. _this._engine = scene.getEngine();
  49460. _this.name = name;
  49461. _this.isRenderTarget = true;
  49462. _this._initialSizeParameter = size;
  49463. _this._processSizeParameter(size);
  49464. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  49465. });
  49466. _this._generateMipMaps = generateMipMaps ? true : false;
  49467. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  49468. // Rendering groups
  49469. _this._renderingManager = new BABYLON.RenderingManager(scene);
  49470. if (isMulti) {
  49471. return _this;
  49472. }
  49473. _this._renderTargetOptions = {
  49474. generateMipMaps: generateMipMaps,
  49475. type: type,
  49476. samplingMode: samplingMode,
  49477. generateDepthBuffer: generateDepthBuffer,
  49478. generateStencilBuffer: generateStencilBuffer
  49479. };
  49480. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  49481. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49482. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49483. }
  49484. if (isCube) {
  49485. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  49486. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  49487. _this._textureMatrix = BABYLON.Matrix.Identity();
  49488. }
  49489. else {
  49490. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  49491. }
  49492. return _this;
  49493. }
  49494. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  49495. get: function () {
  49496. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  49497. },
  49498. enumerable: true,
  49499. configurable: true
  49500. });
  49501. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  49502. get: function () {
  49503. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  49504. },
  49505. enumerable: true,
  49506. configurable: true
  49507. });
  49508. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  49509. get: function () {
  49510. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  49511. },
  49512. enumerable: true,
  49513. configurable: true
  49514. });
  49515. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  49516. set: function (callback) {
  49517. if (this._onAfterUnbindObserver) {
  49518. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  49519. }
  49520. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  49521. },
  49522. enumerable: true,
  49523. configurable: true
  49524. });
  49525. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  49526. set: function (callback) {
  49527. if (this._onBeforeRenderObserver) {
  49528. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49529. }
  49530. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  49531. },
  49532. enumerable: true,
  49533. configurable: true
  49534. });
  49535. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  49536. set: function (callback) {
  49537. if (this._onAfterRenderObserver) {
  49538. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  49539. }
  49540. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  49541. },
  49542. enumerable: true,
  49543. configurable: true
  49544. });
  49545. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  49546. set: function (callback) {
  49547. if (this._onClearObserver) {
  49548. this.onClearObservable.remove(this._onClearObserver);
  49549. }
  49550. this._onClearObserver = this.onClearObservable.add(callback);
  49551. },
  49552. enumerable: true,
  49553. configurable: true
  49554. });
  49555. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  49556. get: function () {
  49557. return this._renderTargetOptions;
  49558. },
  49559. enumerable: true,
  49560. configurable: true
  49561. });
  49562. RenderTargetTexture.prototype._onRatioRescale = function () {
  49563. if (this._sizeRatio) {
  49564. this.resize(this._initialSizeParameter);
  49565. }
  49566. };
  49567. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  49568. if (size.ratio) {
  49569. this._sizeRatio = size.ratio;
  49570. this._size = {
  49571. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  49572. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  49573. };
  49574. }
  49575. else {
  49576. this._size = size;
  49577. }
  49578. };
  49579. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  49580. get: function () {
  49581. return this._samples;
  49582. },
  49583. set: function (value) {
  49584. if (this._samples === value) {
  49585. return;
  49586. }
  49587. var scene = this.getScene();
  49588. if (!scene) {
  49589. return;
  49590. }
  49591. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  49592. },
  49593. enumerable: true,
  49594. configurable: true
  49595. });
  49596. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  49597. this._currentRefreshId = -1;
  49598. };
  49599. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  49600. get: function () {
  49601. return this._refreshRate;
  49602. },
  49603. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49604. set: function (value) {
  49605. this._refreshRate = value;
  49606. this.resetRefreshCounter();
  49607. },
  49608. enumerable: true,
  49609. configurable: true
  49610. });
  49611. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  49612. if (!this._postProcessManager) {
  49613. var scene = this.getScene();
  49614. if (!scene) {
  49615. return;
  49616. }
  49617. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  49618. this._postProcesses = new Array();
  49619. }
  49620. this._postProcesses.push(postProcess);
  49621. this._postProcesses[0].autoClear = false;
  49622. };
  49623. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  49624. if (!this._postProcesses) {
  49625. return;
  49626. }
  49627. if (dispose) {
  49628. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  49629. var postProcess = _a[_i];
  49630. postProcess.dispose();
  49631. }
  49632. }
  49633. this._postProcesses = [];
  49634. };
  49635. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  49636. if (!this._postProcesses) {
  49637. return;
  49638. }
  49639. var index = this._postProcesses.indexOf(postProcess);
  49640. if (index === -1) {
  49641. return;
  49642. }
  49643. this._postProcesses.splice(index, 1);
  49644. if (this._postProcesses.length > 0) {
  49645. this._postProcesses[0].autoClear = false;
  49646. }
  49647. };
  49648. RenderTargetTexture.prototype._shouldRender = function () {
  49649. if (this._currentRefreshId === -1) {
  49650. this._currentRefreshId = 1;
  49651. return true;
  49652. }
  49653. if (this.refreshRate === this._currentRefreshId) {
  49654. this._currentRefreshId = 1;
  49655. return true;
  49656. }
  49657. this._currentRefreshId++;
  49658. return false;
  49659. };
  49660. RenderTargetTexture.prototype.getRenderSize = function () {
  49661. if (this._size.width) {
  49662. return this._size.width;
  49663. }
  49664. return this._size;
  49665. };
  49666. RenderTargetTexture.prototype.getRenderWidth = function () {
  49667. if (this._size.width) {
  49668. return this._size.width;
  49669. }
  49670. return this._size;
  49671. };
  49672. RenderTargetTexture.prototype.getRenderHeight = function () {
  49673. if (this._size.width) {
  49674. return this._size.height;
  49675. }
  49676. return this._size;
  49677. };
  49678. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  49679. get: function () {
  49680. return true;
  49681. },
  49682. enumerable: true,
  49683. configurable: true
  49684. });
  49685. RenderTargetTexture.prototype.scale = function (ratio) {
  49686. var newSize = this.getRenderSize() * ratio;
  49687. this.resize(newSize);
  49688. };
  49689. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  49690. if (this.isCube) {
  49691. return this._textureMatrix;
  49692. }
  49693. return _super.prototype.getReflectionTextureMatrix.call(this);
  49694. };
  49695. RenderTargetTexture.prototype.resize = function (size) {
  49696. this.releaseInternalTexture();
  49697. var scene = this.getScene();
  49698. if (!scene) {
  49699. return;
  49700. }
  49701. this._processSizeParameter(size);
  49702. if (this.isCube) {
  49703. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  49704. }
  49705. else {
  49706. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  49707. }
  49708. };
  49709. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  49710. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  49711. if (dumpForDebug === void 0) { dumpForDebug = false; }
  49712. var scene = this.getScene();
  49713. if (!scene) {
  49714. return;
  49715. }
  49716. var engine = scene.getEngine();
  49717. if (this.useCameraPostProcesses !== undefined) {
  49718. useCameraPostProcess = this.useCameraPostProcesses;
  49719. }
  49720. if (this._waitingRenderList) {
  49721. this.renderList = [];
  49722. for (var index = 0; index < this._waitingRenderList.length; index++) {
  49723. var id = this._waitingRenderList[index];
  49724. var mesh_1 = scene.getMeshByID(id);
  49725. if (mesh_1) {
  49726. this.renderList.push(mesh_1);
  49727. }
  49728. }
  49729. delete this._waitingRenderList;
  49730. }
  49731. // Is predicate defined?
  49732. if (this.renderListPredicate) {
  49733. if (this.renderList) {
  49734. this.renderList.splice(0); // Clear previous renderList
  49735. }
  49736. else {
  49737. this.renderList = [];
  49738. }
  49739. var scene = this.getScene();
  49740. if (!scene) {
  49741. return;
  49742. }
  49743. var sceneMeshes = scene.meshes;
  49744. for (var index = 0; index < sceneMeshes.length; index++) {
  49745. var mesh = sceneMeshes[index];
  49746. if (this.renderListPredicate(mesh)) {
  49747. this.renderList.push(mesh);
  49748. }
  49749. }
  49750. }
  49751. this.onBeforeBindObservable.notifyObservers(this);
  49752. // Set custom projection.
  49753. // Needs to be before binding to prevent changing the aspect ratio.
  49754. var camera;
  49755. if (this.activeCamera) {
  49756. camera = this.activeCamera;
  49757. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  49758. if (this.activeCamera !== scene.activeCamera) {
  49759. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  49760. }
  49761. }
  49762. else {
  49763. camera = scene.activeCamera;
  49764. if (camera) {
  49765. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  49766. }
  49767. }
  49768. // Prepare renderingManager
  49769. this._renderingManager.reset();
  49770. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  49771. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  49772. var sceneRenderId = scene.getRenderId();
  49773. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  49774. var mesh = currentRenderList[meshIndex];
  49775. if (mesh) {
  49776. if (!mesh.isReady()) {
  49777. // Reset _currentRefreshId
  49778. this.resetRefreshCounter();
  49779. continue;
  49780. }
  49781. mesh._preActivateForIntermediateRendering(sceneRenderId);
  49782. var isMasked = void 0;
  49783. if (!this.renderList && camera) {
  49784. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  49785. }
  49786. else {
  49787. isMasked = false;
  49788. }
  49789. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  49790. mesh._activate(sceneRenderId);
  49791. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  49792. var subMesh = mesh.subMeshes[subIndex];
  49793. scene._activeIndices.addCount(subMesh.indexCount, false);
  49794. this._renderingManager.dispatch(subMesh);
  49795. }
  49796. }
  49797. }
  49798. }
  49799. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  49800. var particleSystem = scene.particleSystems[particleIndex];
  49801. var emitter = particleSystem.emitter;
  49802. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  49803. continue;
  49804. }
  49805. if (currentRenderList.indexOf(emitter) >= 0) {
  49806. this._renderingManager.dispatchParticles(particleSystem);
  49807. }
  49808. }
  49809. if (this.isCube) {
  49810. for (var face = 0; face < 6; face++) {
  49811. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49812. scene.incrementRenderId();
  49813. scene.resetCachedMaterial();
  49814. }
  49815. }
  49816. else {
  49817. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  49818. }
  49819. this.onAfterUnbindObservable.notifyObservers(this);
  49820. if (scene.activeCamera) {
  49821. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  49822. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  49823. }
  49824. engine.setViewport(scene.activeCamera.viewport);
  49825. }
  49826. scene.resetCachedMaterial();
  49827. };
  49828. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  49829. var minimum = 128;
  49830. var x = renderDimension * scale;
  49831. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  49832. // Ensure we don't exceed the render dimension (while staying POT)
  49833. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  49834. };
  49835. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  49836. var _this = this;
  49837. var scene = this.getScene();
  49838. if (!scene) {
  49839. return;
  49840. }
  49841. var engine = scene.getEngine();
  49842. if (!this._texture) {
  49843. return;
  49844. }
  49845. // Bind
  49846. if (this._postProcessManager) {
  49847. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  49848. }
  49849. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  49850. if (this._texture) {
  49851. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  49852. }
  49853. }
  49854. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  49855. // Clear
  49856. if (this.onClearObservable.hasObservers()) {
  49857. this.onClearObservable.notifyObservers(engine);
  49858. }
  49859. else {
  49860. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  49861. }
  49862. if (!this._doNotChangeAspectRatio) {
  49863. scene.updateTransformMatrix(true);
  49864. }
  49865. // Render
  49866. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  49867. if (this._postProcessManager) {
  49868. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  49869. }
  49870. else if (useCameraPostProcess) {
  49871. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  49872. }
  49873. if (!this._doNotChangeAspectRatio) {
  49874. scene.updateTransformMatrix(true);
  49875. }
  49876. // Dump ?
  49877. if (dumpForDebug) {
  49878. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  49879. }
  49880. // Unbind
  49881. if (!this.isCube || faceIndex === 5) {
  49882. if (this.isCube) {
  49883. if (faceIndex === 5) {
  49884. engine.generateMipMapsForCubemap(this._texture);
  49885. }
  49886. }
  49887. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  49888. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  49889. });
  49890. }
  49891. else {
  49892. this.onAfterRenderObservable.notifyObservers(faceIndex);
  49893. }
  49894. };
  49895. /**
  49896. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  49897. * This allowed control for front to back rendering or reversly depending of the special needs.
  49898. *
  49899. * @param renderingGroupId The rendering group id corresponding to its index
  49900. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  49901. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  49902. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  49903. */
  49904. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  49905. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  49906. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  49907. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  49908. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  49909. };
  49910. /**
  49911. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  49912. *
  49913. * @param renderingGroupId The rendering group id corresponding to its index
  49914. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  49915. */
  49916. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  49917. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  49918. };
  49919. RenderTargetTexture.prototype.clone = function () {
  49920. var textureSize = this.getSize();
  49921. 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);
  49922. // Base texture
  49923. newTexture.hasAlpha = this.hasAlpha;
  49924. newTexture.level = this.level;
  49925. // RenderTarget Texture
  49926. newTexture.coordinatesMode = this.coordinatesMode;
  49927. if (this.renderList) {
  49928. newTexture.renderList = this.renderList.slice(0);
  49929. }
  49930. return newTexture;
  49931. };
  49932. RenderTargetTexture.prototype.serialize = function () {
  49933. if (!this.name) {
  49934. return null;
  49935. }
  49936. var serializationObject = _super.prototype.serialize.call(this);
  49937. serializationObject.renderTargetSize = this.getRenderSize();
  49938. serializationObject.renderList = [];
  49939. if (this.renderList) {
  49940. for (var index = 0; index < this.renderList.length; index++) {
  49941. serializationObject.renderList.push(this.renderList[index].id);
  49942. }
  49943. }
  49944. return serializationObject;
  49945. };
  49946. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  49947. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  49948. var objBuffer = this.getInternalTexture();
  49949. var scene = this.getScene();
  49950. if (objBuffer && scene) {
  49951. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  49952. }
  49953. };
  49954. RenderTargetTexture.prototype.dispose = function () {
  49955. if (this._postProcessManager) {
  49956. this._postProcessManager.dispose();
  49957. this._postProcessManager = null;
  49958. }
  49959. this.clearPostProcesses(true);
  49960. if (this._resizeObserver) {
  49961. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  49962. this._resizeObserver = null;
  49963. }
  49964. this.renderList = null;
  49965. // Remove from custom render targets
  49966. var scene = this.getScene();
  49967. if (!scene) {
  49968. return;
  49969. }
  49970. var index = scene.customRenderTargets.indexOf(this);
  49971. if (index >= 0) {
  49972. scene.customRenderTargets.splice(index, 1);
  49973. }
  49974. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  49975. var camera = _a[_i];
  49976. index = camera.customRenderTargets.indexOf(this);
  49977. if (index >= 0) {
  49978. camera.customRenderTargets.splice(index, 1);
  49979. }
  49980. }
  49981. _super.prototype.dispose.call(this);
  49982. };
  49983. RenderTargetTexture.prototype._rebuild = function () {
  49984. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  49985. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  49986. }
  49987. if (this._postProcessManager) {
  49988. this._postProcessManager._rebuild();
  49989. }
  49990. };
  49991. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  49992. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  49993. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  49994. return RenderTargetTexture;
  49995. }(BABYLON.Texture));
  49996. BABYLON.RenderTargetTexture = RenderTargetTexture;
  49997. })(BABYLON || (BABYLON = {}));
  49998. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  49999. var BABYLON;
  50000. (function (BABYLON) {
  50001. ;
  50002. var MultiRenderTarget = /** @class */ (function (_super) {
  50003. __extends(MultiRenderTarget, _super);
  50004. function MultiRenderTarget(name, size, count, scene, options) {
  50005. var _this = this;
  50006. options = options || {};
  50007. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  50008. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  50009. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  50010. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  50011. _this._engine = scene.getEngine();
  50012. if (!_this.isSupported) {
  50013. _this.dispose();
  50014. return;
  50015. }
  50016. var types = [];
  50017. var samplingModes = [];
  50018. for (var i = 0; i < count; i++) {
  50019. if (options.types && options.types[i]) {
  50020. types.push(options.types[i]);
  50021. }
  50022. else {
  50023. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  50024. }
  50025. if (options.samplingModes && options.samplingModes[i]) {
  50026. samplingModes.push(options.samplingModes[i]);
  50027. }
  50028. else {
  50029. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50030. }
  50031. }
  50032. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  50033. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  50034. _this._count = count;
  50035. _this._size = size;
  50036. _this._multiRenderTargetOptions = {
  50037. samplingModes: samplingModes,
  50038. generateMipMaps: generateMipMaps,
  50039. generateDepthBuffer: generateDepthBuffer,
  50040. generateStencilBuffer: generateStencilBuffer,
  50041. generateDepthTexture: generateDepthTexture,
  50042. types: types,
  50043. textureCount: count
  50044. };
  50045. _this._createInternalTextures();
  50046. _this._createTextures();
  50047. return _this;
  50048. }
  50049. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  50050. get: function () {
  50051. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  50052. },
  50053. enumerable: true,
  50054. configurable: true
  50055. });
  50056. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  50057. get: function () {
  50058. return this._textures;
  50059. },
  50060. enumerable: true,
  50061. configurable: true
  50062. });
  50063. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  50064. get: function () {
  50065. return this._textures[this._textures.length - 1];
  50066. },
  50067. enumerable: true,
  50068. configurable: true
  50069. });
  50070. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  50071. set: function (wrap) {
  50072. if (this._textures) {
  50073. for (var i = 0; i < this._textures.length; i++) {
  50074. this._textures[i].wrapU = wrap;
  50075. }
  50076. }
  50077. },
  50078. enumerable: true,
  50079. configurable: true
  50080. });
  50081. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  50082. set: function (wrap) {
  50083. if (this._textures) {
  50084. for (var i = 0; i < this._textures.length; i++) {
  50085. this._textures[i].wrapV = wrap;
  50086. }
  50087. }
  50088. },
  50089. enumerable: true,
  50090. configurable: true
  50091. });
  50092. MultiRenderTarget.prototype._rebuild = function () {
  50093. this.releaseInternalTextures();
  50094. this._createInternalTextures();
  50095. for (var i = 0; i < this._internalTextures.length; i++) {
  50096. var texture = this._textures[i];
  50097. texture._texture = this._internalTextures[i];
  50098. }
  50099. // Keeps references to frame buffer and stencil/depth buffer
  50100. this._texture = this._internalTextures[0];
  50101. };
  50102. MultiRenderTarget.prototype._createInternalTextures = function () {
  50103. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  50104. };
  50105. MultiRenderTarget.prototype._createTextures = function () {
  50106. this._textures = [];
  50107. for (var i = 0; i < this._internalTextures.length; i++) {
  50108. var texture = new BABYLON.Texture(null, this.getScene());
  50109. texture._texture = this._internalTextures[i];
  50110. this._textures.push(texture);
  50111. }
  50112. // Keeps references to frame buffer and stencil/depth buffer
  50113. this._texture = this._internalTextures[0];
  50114. };
  50115. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  50116. get: function () {
  50117. return this._samples;
  50118. },
  50119. set: function (value) {
  50120. if (this._samples === value) {
  50121. return;
  50122. }
  50123. for (var i = 0; i < this._internalTextures.length; i++) {
  50124. this._samples = this._engine.updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  50125. }
  50126. },
  50127. enumerable: true,
  50128. configurable: true
  50129. });
  50130. MultiRenderTarget.prototype.resize = function (size) {
  50131. this.releaseInternalTextures();
  50132. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  50133. this._createInternalTextures();
  50134. };
  50135. MultiRenderTarget.prototype.dispose = function () {
  50136. this.releaseInternalTextures();
  50137. _super.prototype.dispose.call(this);
  50138. };
  50139. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  50140. if (!this._internalTextures) {
  50141. return;
  50142. }
  50143. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  50144. if (this._internalTextures[i] !== undefined) {
  50145. this._internalTextures[i].dispose();
  50146. this._internalTextures.splice(i, 1);
  50147. }
  50148. }
  50149. };
  50150. return MultiRenderTarget;
  50151. }(BABYLON.RenderTargetTexture));
  50152. BABYLON.MultiRenderTarget = MultiRenderTarget;
  50153. })(BABYLON || (BABYLON = {}));
  50154. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  50155. var BABYLON;
  50156. (function (BABYLON) {
  50157. var MirrorTexture = /** @class */ (function (_super) {
  50158. __extends(MirrorTexture, _super);
  50159. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  50160. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50161. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  50162. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  50163. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  50164. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  50165. _this._transformMatrix = BABYLON.Matrix.Zero();
  50166. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  50167. _this._adaptiveBlurKernel = 0;
  50168. _this._blurKernelX = 0;
  50169. _this._blurKernelY = 0;
  50170. _this._blurRatio = 1.0;
  50171. _this.ignoreCameraViewport = true;
  50172. _this.onBeforeRenderObservable.add(function () {
  50173. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  50174. _this._savedViewMatrix = scene.getViewMatrix();
  50175. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  50176. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  50177. scene.clipPlane = _this.mirrorPlane;
  50178. scene.getEngine().cullBackFaces = false;
  50179. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  50180. });
  50181. _this.onAfterRenderObservable.add(function () {
  50182. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  50183. scene.getEngine().cullBackFaces = true;
  50184. scene._mirroredCameraPosition = null;
  50185. delete scene.clipPlane;
  50186. });
  50187. return _this;
  50188. }
  50189. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  50190. get: function () {
  50191. return this._blurRatio;
  50192. },
  50193. set: function (value) {
  50194. if (this._blurRatio === value) {
  50195. return;
  50196. }
  50197. this._blurRatio = value;
  50198. this._preparePostProcesses();
  50199. },
  50200. enumerable: true,
  50201. configurable: true
  50202. });
  50203. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  50204. set: function (value) {
  50205. this._adaptiveBlurKernel = value;
  50206. this._autoComputeBlurKernel();
  50207. },
  50208. enumerable: true,
  50209. configurable: true
  50210. });
  50211. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  50212. set: function (value) {
  50213. this.blurKernelX = value;
  50214. this.blurKernelY = value;
  50215. },
  50216. enumerable: true,
  50217. configurable: true
  50218. });
  50219. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  50220. get: function () {
  50221. return this._blurKernelX;
  50222. },
  50223. set: function (value) {
  50224. if (this._blurKernelX === value) {
  50225. return;
  50226. }
  50227. this._blurKernelX = value;
  50228. this._preparePostProcesses();
  50229. },
  50230. enumerable: true,
  50231. configurable: true
  50232. });
  50233. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  50234. get: function () {
  50235. return this._blurKernelY;
  50236. },
  50237. set: function (value) {
  50238. if (this._blurKernelY === value) {
  50239. return;
  50240. }
  50241. this._blurKernelY = value;
  50242. this._preparePostProcesses();
  50243. },
  50244. enumerable: true,
  50245. configurable: true
  50246. });
  50247. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  50248. var engine = this.getScene().getEngine();
  50249. var dw = this.getRenderWidth() / engine.getRenderWidth();
  50250. var dh = this.getRenderHeight() / engine.getRenderHeight();
  50251. this.blurKernelX = this._adaptiveBlurKernel * dw;
  50252. this.blurKernelY = this._adaptiveBlurKernel * dh;
  50253. };
  50254. MirrorTexture.prototype._onRatioRescale = function () {
  50255. if (this._sizeRatio) {
  50256. this.resize(this._initialSizeParameter);
  50257. if (!this._adaptiveBlurKernel) {
  50258. this._preparePostProcesses();
  50259. }
  50260. }
  50261. if (this._adaptiveBlurKernel) {
  50262. this._autoComputeBlurKernel();
  50263. }
  50264. };
  50265. MirrorTexture.prototype._preparePostProcesses = function () {
  50266. this.clearPostProcesses(true);
  50267. if (this._blurKernelX && this._blurKernelY) {
  50268. var engine = this.getScene().getEngine();
  50269. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  50270. 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);
  50271. this._blurX.autoClear = false;
  50272. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  50273. this._blurX.outputTexture = this._texture;
  50274. }
  50275. else {
  50276. this._blurX.alwaysForcePOT = true;
  50277. }
  50278. 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);
  50279. this._blurY.autoClear = false;
  50280. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  50281. this.addPostProcess(this._blurX);
  50282. this.addPostProcess(this._blurY);
  50283. }
  50284. };
  50285. MirrorTexture.prototype.clone = function () {
  50286. var scene = this.getScene();
  50287. if (!scene) {
  50288. return this;
  50289. }
  50290. var textureSize = this.getSize();
  50291. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  50292. // Base texture
  50293. newTexture.hasAlpha = this.hasAlpha;
  50294. newTexture.level = this.level;
  50295. // Mirror Texture
  50296. newTexture.mirrorPlane = this.mirrorPlane.clone();
  50297. if (this.renderList) {
  50298. newTexture.renderList = this.renderList.slice(0);
  50299. }
  50300. return newTexture;
  50301. };
  50302. MirrorTexture.prototype.serialize = function () {
  50303. if (!this.name) {
  50304. return null;
  50305. }
  50306. var serializationObject = _super.prototype.serialize.call(this);
  50307. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  50308. return serializationObject;
  50309. };
  50310. return MirrorTexture;
  50311. }(BABYLON.RenderTargetTexture));
  50312. BABYLON.MirrorTexture = MirrorTexture;
  50313. })(BABYLON || (BABYLON = {}));
  50314. //# sourceMappingURL=babylon.mirrorTexture.js.map
  50315. var BABYLON;
  50316. (function (BABYLON) {
  50317. /**
  50318. * Creates a refraction texture used by refraction channel of the standard material.
  50319. * @param name the texture name
  50320. * @param size size of the underlying texture
  50321. * @param scene root scene
  50322. */
  50323. var RefractionTexture = /** @class */ (function (_super) {
  50324. __extends(RefractionTexture, _super);
  50325. function RefractionTexture(name, size, scene, generateMipMaps) {
  50326. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  50327. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  50328. _this.depth = 2.0;
  50329. _this.onBeforeRenderObservable.add(function () {
  50330. scene.clipPlane = _this.refractionPlane;
  50331. });
  50332. _this.onAfterRenderObservable.add(function () {
  50333. delete scene.clipPlane;
  50334. });
  50335. return _this;
  50336. }
  50337. RefractionTexture.prototype.clone = function () {
  50338. var scene = this.getScene();
  50339. if (!scene) {
  50340. return this;
  50341. }
  50342. var textureSize = this.getSize();
  50343. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  50344. // Base texture
  50345. newTexture.hasAlpha = this.hasAlpha;
  50346. newTexture.level = this.level;
  50347. // Refraction Texture
  50348. newTexture.refractionPlane = this.refractionPlane.clone();
  50349. if (this.renderList) {
  50350. newTexture.renderList = this.renderList.slice(0);
  50351. }
  50352. newTexture.depth = this.depth;
  50353. return newTexture;
  50354. };
  50355. RefractionTexture.prototype.serialize = function () {
  50356. if (!this.name) {
  50357. return null;
  50358. }
  50359. var serializationObject = _super.prototype.serialize.call(this);
  50360. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  50361. serializationObject.depth = this.depth;
  50362. return serializationObject;
  50363. };
  50364. return RefractionTexture;
  50365. }(BABYLON.RenderTargetTexture));
  50366. BABYLON.RefractionTexture = RefractionTexture;
  50367. })(BABYLON || (BABYLON = {}));
  50368. //# sourceMappingURL=babylon.refractionTexture.js.map
  50369. var BABYLON;
  50370. (function (BABYLON) {
  50371. var DynamicTexture = /** @class */ (function (_super) {
  50372. __extends(DynamicTexture, _super);
  50373. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  50374. if (scene === void 0) { scene = null; }
  50375. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50376. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  50377. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  50378. _this.name = name;
  50379. _this._engine = _this.getScene().getEngine();
  50380. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50381. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50382. _this._generateMipMaps = generateMipMaps;
  50383. if (options.getContext) {
  50384. _this._canvas = options;
  50385. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50386. }
  50387. else {
  50388. _this._canvas = document.createElement("canvas");
  50389. if (options.width) {
  50390. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  50391. }
  50392. else {
  50393. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  50394. }
  50395. }
  50396. var textureSize = _this.getSize();
  50397. _this._canvas.width = textureSize.width;
  50398. _this._canvas.height = textureSize.height;
  50399. _this._context = _this._canvas.getContext("2d");
  50400. return _this;
  50401. }
  50402. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  50403. get: function () {
  50404. return true;
  50405. },
  50406. enumerable: true,
  50407. configurable: true
  50408. });
  50409. DynamicTexture.prototype._recreate = function (textureSize) {
  50410. this._canvas.width = textureSize.width;
  50411. this._canvas.height = textureSize.height;
  50412. this.releaseInternalTexture();
  50413. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  50414. };
  50415. DynamicTexture.prototype.scale = function (ratio) {
  50416. var textureSize = this.getSize();
  50417. textureSize.width *= ratio;
  50418. textureSize.height *= ratio;
  50419. this._recreate(textureSize);
  50420. };
  50421. DynamicTexture.prototype.scaleTo = function (width, height) {
  50422. var textureSize = this.getSize();
  50423. textureSize.width = width;
  50424. textureSize.height = height;
  50425. this._recreate(textureSize);
  50426. };
  50427. DynamicTexture.prototype.getContext = function () {
  50428. return this._context;
  50429. };
  50430. DynamicTexture.prototype.clear = function () {
  50431. var size = this.getSize();
  50432. this._context.fillRect(0, 0, size.width, size.height);
  50433. };
  50434. DynamicTexture.prototype.update = function (invertY) {
  50435. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  50436. };
  50437. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  50438. if (update === void 0) { update = true; }
  50439. var size = this.getSize();
  50440. if (clearColor) {
  50441. this._context.fillStyle = clearColor;
  50442. this._context.fillRect(0, 0, size.width, size.height);
  50443. }
  50444. this._context.font = font;
  50445. if (x === null || x === undefined) {
  50446. var textSize = this._context.measureText(text);
  50447. x = (size.width - textSize.width) / 2;
  50448. }
  50449. if (y === null || y === undefined) {
  50450. var fontSize = parseInt((font.replace(/\D/g, '')));
  50451. ;
  50452. y = (size.height / 2) + (fontSize / 3.65);
  50453. }
  50454. this._context.fillStyle = color;
  50455. this._context.fillText(text, x, y);
  50456. if (update) {
  50457. this.update(invertY);
  50458. }
  50459. };
  50460. DynamicTexture.prototype.clone = function () {
  50461. var scene = this.getScene();
  50462. if (!scene) {
  50463. return this;
  50464. }
  50465. var textureSize = this.getSize();
  50466. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  50467. // Base texture
  50468. newTexture.hasAlpha = this.hasAlpha;
  50469. newTexture.level = this.level;
  50470. // Dynamic Texture
  50471. newTexture.wrapU = this.wrapU;
  50472. newTexture.wrapV = this.wrapV;
  50473. return newTexture;
  50474. };
  50475. DynamicTexture.prototype._rebuild = function () {
  50476. this.update();
  50477. };
  50478. return DynamicTexture;
  50479. }(BABYLON.Texture));
  50480. BABYLON.DynamicTexture = DynamicTexture;
  50481. })(BABYLON || (BABYLON = {}));
  50482. //# sourceMappingURL=babylon.dynamicTexture.js.map
  50483. var BABYLON;
  50484. (function (BABYLON) {
  50485. var VideoTexture = /** @class */ (function (_super) {
  50486. __extends(VideoTexture, _super);
  50487. /**
  50488. * Creates a video texture.
  50489. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  50490. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  50491. * @param {BABYLON.Scene} scene is obviously the current scene.
  50492. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  50493. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  50494. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  50495. */
  50496. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  50497. if (generateMipMaps === void 0) { generateMipMaps = false; }
  50498. if (invertY === void 0) { invertY = false; }
  50499. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50500. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50501. _this._autoLaunch = true;
  50502. var urls = null;
  50503. _this.name = name;
  50504. if (urlsOrVideo instanceof HTMLVideoElement) {
  50505. _this.video = urlsOrVideo;
  50506. }
  50507. else {
  50508. urls = urlsOrVideo;
  50509. _this.video = document.createElement("video");
  50510. _this.video.autoplay = false;
  50511. _this.video.loop = true;
  50512. }
  50513. _this._engine = _this.getScene().getEngine();
  50514. _this._generateMipMaps = generateMipMaps;
  50515. _this._samplingMode = samplingMode;
  50516. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  50517. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  50518. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  50519. }
  50520. else {
  50521. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50522. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50523. _this._generateMipMaps = false;
  50524. }
  50525. if (urls) {
  50526. _this.video.addEventListener("canplay", function () {
  50527. _this._createTexture();
  50528. });
  50529. urls.forEach(function (url) {
  50530. var source = document.createElement("source");
  50531. source.src = url;
  50532. _this.video.appendChild(source);
  50533. });
  50534. }
  50535. else {
  50536. _this._createTexture();
  50537. }
  50538. _this._lastUpdate = BABYLON.Tools.Now;
  50539. return _this;
  50540. }
  50541. VideoTexture.prototype.__setTextureReady = function () {
  50542. if (this._texture) {
  50543. this._texture.isReady = true;
  50544. }
  50545. };
  50546. VideoTexture.prototype._createTexture = function () {
  50547. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  50548. if (this._autoLaunch) {
  50549. this._autoLaunch = false;
  50550. this.video.play();
  50551. }
  50552. this._setTextureReady = this.__setTextureReady.bind(this);
  50553. this.video.addEventListener("playing", this._setTextureReady);
  50554. };
  50555. VideoTexture.prototype._rebuild = function () {
  50556. this.update();
  50557. };
  50558. VideoTexture.prototype.update = function () {
  50559. var now = BABYLON.Tools.Now;
  50560. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  50561. return false;
  50562. }
  50563. this._lastUpdate = now;
  50564. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  50565. return true;
  50566. };
  50567. VideoTexture.prototype.dispose = function () {
  50568. _super.prototype.dispose.call(this);
  50569. this.video.removeEventListener("playing", this._setTextureReady);
  50570. };
  50571. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  50572. var video = document.createElement("video");
  50573. var constraintsDeviceId;
  50574. if (constraints && constraints.deviceId) {
  50575. constraintsDeviceId = {
  50576. exact: constraints.deviceId
  50577. };
  50578. }
  50579. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  50580. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  50581. if (navigator.getUserMedia) {
  50582. navigator.getUserMedia({
  50583. video: {
  50584. deviceId: constraintsDeviceId,
  50585. width: {
  50586. min: (constraints && constraints.minWidth) || 256,
  50587. max: (constraints && constraints.maxWidth) || 640
  50588. },
  50589. height: {
  50590. min: (constraints && constraints.minHeight) || 256,
  50591. max: (constraints && constraints.maxHeight) || 480
  50592. }
  50593. }
  50594. }, function (stream) {
  50595. if (video.mozSrcObject !== undefined) {
  50596. video.mozSrcObject = stream;
  50597. }
  50598. else {
  50599. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  50600. }
  50601. video.play();
  50602. if (onReady) {
  50603. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  50604. }
  50605. }, function (e) {
  50606. BABYLON.Tools.Error(e.name);
  50607. });
  50608. }
  50609. };
  50610. return VideoTexture;
  50611. }(BABYLON.Texture));
  50612. BABYLON.VideoTexture = VideoTexture;
  50613. })(BABYLON || (BABYLON = {}));
  50614. //# sourceMappingURL=babylon.videoTexture.js.map
  50615. var BABYLON;
  50616. (function (BABYLON) {
  50617. var RawTexture = /** @class */ (function (_super) {
  50618. __extends(RawTexture, _super);
  50619. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  50620. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50621. if (invertY === void 0) { invertY = false; }
  50622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50623. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  50624. _this.format = format;
  50625. _this._engine = scene.getEngine();
  50626. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  50627. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50628. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50629. return _this;
  50630. }
  50631. RawTexture.prototype.update = function (data) {
  50632. this._engine.updateRawTexture(this._texture, data, this.format, this._invertY);
  50633. };
  50634. // Statics
  50635. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50636. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50637. if (invertY === void 0) { invertY = false; }
  50638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50639. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  50640. };
  50641. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50642. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50643. if (invertY === void 0) { invertY = false; }
  50644. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50645. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50646. };
  50647. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50648. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50649. if (invertY === void 0) { invertY = false; }
  50650. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50651. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  50652. };
  50653. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50654. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50655. if (invertY === void 0) { invertY = false; }
  50656. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50657. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  50658. };
  50659. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  50660. if (generateMipMaps === void 0) { generateMipMaps = true; }
  50661. if (invertY === void 0) { invertY = false; }
  50662. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  50663. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  50664. };
  50665. return RawTexture;
  50666. }(BABYLON.Texture));
  50667. BABYLON.RawTexture = RawTexture;
  50668. })(BABYLON || (BABYLON = {}));
  50669. //# sourceMappingURL=babylon.rawTexture.js.map
  50670. var BABYLON;
  50671. (function (BABYLON) {
  50672. var PostProcess = /** @class */ (function () {
  50673. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  50674. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  50675. if (defines === void 0) { defines = null; }
  50676. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  50677. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  50678. if (blockCompilation === void 0) { blockCompilation = false; }
  50679. this.name = name;
  50680. this.width = -1;
  50681. this.height = -1;
  50682. this.autoClear = true;
  50683. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  50684. /*
  50685. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  50686. Can only be used on a single postprocess or on the last one of a chain.
  50687. */
  50688. this.enablePixelPerfectMode = false;
  50689. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  50690. this.alwaysForcePOT = false;
  50691. this.samples = 1;
  50692. this.adaptScaleToCurrentViewport = false;
  50693. this._reusable = false;
  50694. this._textures = new BABYLON.SmartArray(2);
  50695. this._currentRenderTextureInd = 0;
  50696. this._scaleRatio = new BABYLON.Vector2(1, 1);
  50697. this._texelSize = BABYLON.Vector2.Zero();
  50698. // Events
  50699. /**
  50700. * An event triggered when the postprocess is activated.
  50701. * @type {BABYLON.Observable}
  50702. */
  50703. this.onActivateObservable = new BABYLON.Observable();
  50704. /**
  50705. * An event triggered when the postprocess changes its size.
  50706. * @type {BABYLON.Observable}
  50707. */
  50708. this.onSizeChangedObservable = new BABYLON.Observable();
  50709. /**
  50710. * An event triggered when the postprocess applies its effect.
  50711. * @type {BABYLON.Observable}
  50712. */
  50713. this.onApplyObservable = new BABYLON.Observable();
  50714. /**
  50715. * An event triggered before rendering the postprocess
  50716. * @type {BABYLON.Observable}
  50717. */
  50718. this.onBeforeRenderObservable = new BABYLON.Observable();
  50719. /**
  50720. * An event triggered after rendering the postprocess
  50721. * @type {BABYLON.Observable}
  50722. */
  50723. this.onAfterRenderObservable = new BABYLON.Observable();
  50724. if (camera != null) {
  50725. this._camera = camera;
  50726. this._scene = camera.getScene();
  50727. camera.attachPostProcess(this);
  50728. this._engine = this._scene.getEngine();
  50729. this._scene.postProcesses.push(this);
  50730. }
  50731. else if (engine) {
  50732. this._engine = engine;
  50733. this._engine.postProcesses.push(this);
  50734. }
  50735. this._options = options;
  50736. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  50737. this._reusable = reusable || false;
  50738. this._textureType = textureType;
  50739. this._samplers = samplers || [];
  50740. this._samplers.push("textureSampler");
  50741. this._fragmentUrl = fragmentUrl;
  50742. this._vertexUrl = vertexUrl;
  50743. this._parameters = parameters || [];
  50744. this._parameters.push("scale");
  50745. this._indexParameters = indexParameters;
  50746. if (!blockCompilation) {
  50747. this.updateEffect(defines);
  50748. }
  50749. }
  50750. Object.defineProperty(PostProcess.prototype, "onActivate", {
  50751. set: function (callback) {
  50752. if (this._onActivateObserver) {
  50753. this.onActivateObservable.remove(this._onActivateObserver);
  50754. }
  50755. if (callback) {
  50756. this._onActivateObserver = this.onActivateObservable.add(callback);
  50757. }
  50758. },
  50759. enumerable: true,
  50760. configurable: true
  50761. });
  50762. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  50763. set: function (callback) {
  50764. if (this._onSizeChangedObserver) {
  50765. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  50766. }
  50767. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  50768. },
  50769. enumerable: true,
  50770. configurable: true
  50771. });
  50772. Object.defineProperty(PostProcess.prototype, "onApply", {
  50773. set: function (callback) {
  50774. if (this._onApplyObserver) {
  50775. this.onApplyObservable.remove(this._onApplyObserver);
  50776. }
  50777. this._onApplyObserver = this.onApplyObservable.add(callback);
  50778. },
  50779. enumerable: true,
  50780. configurable: true
  50781. });
  50782. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  50783. set: function (callback) {
  50784. if (this._onBeforeRenderObserver) {
  50785. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  50786. }
  50787. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  50788. },
  50789. enumerable: true,
  50790. configurable: true
  50791. });
  50792. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  50793. set: function (callback) {
  50794. if (this._onAfterRenderObserver) {
  50795. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  50796. }
  50797. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  50798. },
  50799. enumerable: true,
  50800. configurable: true
  50801. });
  50802. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  50803. get: function () {
  50804. return this._textures.data[this._currentRenderTextureInd];
  50805. },
  50806. set: function (value) {
  50807. this._forcedOutputTexture = value;
  50808. },
  50809. enumerable: true,
  50810. configurable: true
  50811. });
  50812. PostProcess.prototype.getCamera = function () {
  50813. return this._camera;
  50814. };
  50815. Object.defineProperty(PostProcess.prototype, "texelSize", {
  50816. get: function () {
  50817. if (this._shareOutputWithPostProcess) {
  50818. return this._shareOutputWithPostProcess.texelSize;
  50819. }
  50820. if (this._forcedOutputTexture) {
  50821. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  50822. }
  50823. return this._texelSize;
  50824. },
  50825. enumerable: true,
  50826. configurable: true
  50827. });
  50828. PostProcess.prototype.getEngine = function () {
  50829. return this._engine;
  50830. };
  50831. PostProcess.prototype.getEffect = function () {
  50832. return this._effect;
  50833. };
  50834. PostProcess.prototype.shareOutputWith = function (postProcess) {
  50835. this._disposeTextures();
  50836. this._shareOutputWithPostProcess = postProcess;
  50837. return this;
  50838. };
  50839. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  50840. if (defines === void 0) { defines = null; }
  50841. if (uniforms === void 0) { uniforms = null; }
  50842. if (samplers === void 0) { samplers = null; }
  50843. 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);
  50844. };
  50845. PostProcess.prototype.isReusable = function () {
  50846. return this._reusable;
  50847. };
  50848. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  50849. PostProcess.prototype.markTextureDirty = function () {
  50850. this.width = -1;
  50851. };
  50852. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  50853. var _this = this;
  50854. if (sourceTexture === void 0) { sourceTexture = null; }
  50855. camera = camera || this._camera;
  50856. var scene = camera.getScene();
  50857. var engine = scene.getEngine();
  50858. var maxSize = engine.getCaps().maxTextureSize;
  50859. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  50860. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  50861. var desiredWidth = (this._options.width || requiredWidth);
  50862. var desiredHeight = this._options.height || requiredHeight;
  50863. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  50864. if (this.adaptScaleToCurrentViewport) {
  50865. var currentViewport = engine.currentViewport;
  50866. if (currentViewport) {
  50867. desiredWidth *= currentViewport.width;
  50868. desiredHeight *= currentViewport.height;
  50869. }
  50870. }
  50871. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  50872. if (!this._options.width) {
  50873. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  50874. }
  50875. if (!this._options.height) {
  50876. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  50877. }
  50878. }
  50879. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  50880. if (this._textures.length > 0) {
  50881. for (var i = 0; i < this._textures.length; i++) {
  50882. this._engine._releaseTexture(this._textures.data[i]);
  50883. }
  50884. this._textures.reset();
  50885. }
  50886. this.width = desiredWidth;
  50887. this.height = desiredHeight;
  50888. var textureSize = { width: this.width, height: this.height };
  50889. var textureOptions = {
  50890. generateMipMaps: false,
  50891. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  50892. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  50893. samplingMode: this.renderTargetSamplingMode,
  50894. type: this._textureType
  50895. };
  50896. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50897. if (this._reusable) {
  50898. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  50899. }
  50900. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  50901. this.onSizeChangedObservable.notifyObservers(this);
  50902. }
  50903. this._textures.forEach(function (texture) {
  50904. if (texture.samples !== _this.samples) {
  50905. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  50906. }
  50907. });
  50908. }
  50909. var target;
  50910. if (this._shareOutputWithPostProcess) {
  50911. target = this._shareOutputWithPostProcess.outputTexture;
  50912. }
  50913. else if (this._forcedOutputTexture) {
  50914. target = this._forcedOutputTexture;
  50915. this.width = this._forcedOutputTexture.width;
  50916. this.height = this._forcedOutputTexture.height;
  50917. }
  50918. else {
  50919. target = this.outputTexture;
  50920. }
  50921. if (this.enablePixelPerfectMode) {
  50922. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  50923. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  50924. }
  50925. else {
  50926. this._scaleRatio.copyFromFloats(1, 1);
  50927. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  50928. }
  50929. this.onActivateObservable.notifyObservers(camera);
  50930. // Clear
  50931. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  50932. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  50933. }
  50934. if (this._reusable) {
  50935. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  50936. }
  50937. };
  50938. Object.defineProperty(PostProcess.prototype, "isSupported", {
  50939. get: function () {
  50940. return this._effect.isSupported;
  50941. },
  50942. enumerable: true,
  50943. configurable: true
  50944. });
  50945. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  50946. get: function () {
  50947. if (this._shareOutputWithPostProcess) {
  50948. return this._shareOutputWithPostProcess.aspectRatio;
  50949. }
  50950. if (this._forcedOutputTexture) {
  50951. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  50952. }
  50953. return this.width / this.height;
  50954. },
  50955. enumerable: true,
  50956. configurable: true
  50957. });
  50958. PostProcess.prototype.apply = function () {
  50959. // Check
  50960. if (!this._effect || !this._effect.isReady())
  50961. return null;
  50962. // States
  50963. this._engine.enableEffect(this._effect);
  50964. this._engine.setState(false);
  50965. this._engine.setDepthBuffer(false);
  50966. this._engine.setDepthWrite(false);
  50967. // Alpha
  50968. this._engine.setAlphaMode(this.alphaMode);
  50969. if (this.alphaConstants) {
  50970. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  50971. }
  50972. // Texture
  50973. var source;
  50974. if (this._shareOutputWithPostProcess) {
  50975. source = this._shareOutputWithPostProcess.outputTexture;
  50976. }
  50977. else if (this._forcedOutputTexture) {
  50978. source = this._forcedOutputTexture;
  50979. }
  50980. else {
  50981. source = this.outputTexture;
  50982. }
  50983. this._effect._bindTexture("textureSampler", source);
  50984. // Parameters
  50985. this._effect.setVector2("scale", this._scaleRatio);
  50986. this.onApplyObservable.notifyObservers(this._effect);
  50987. return this._effect;
  50988. };
  50989. PostProcess.prototype._disposeTextures = function () {
  50990. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  50991. return;
  50992. }
  50993. if (this._textures.length > 0) {
  50994. for (var i = 0; i < this._textures.length; i++) {
  50995. this._engine._releaseTexture(this._textures.data[i]);
  50996. }
  50997. }
  50998. this._textures.dispose();
  50999. };
  51000. PostProcess.prototype.dispose = function (camera) {
  51001. camera = camera || this._camera;
  51002. this._disposeTextures();
  51003. if (this._scene) {
  51004. var index_1 = this._scene.postProcesses.indexOf(this);
  51005. if (index_1 !== -1) {
  51006. this._scene.postProcesses.splice(index_1, 1);
  51007. }
  51008. }
  51009. else {
  51010. var index_2 = this._engine.postProcesses.indexOf(this);
  51011. if (index_2 !== -1) {
  51012. this._engine.postProcesses.splice(index_2, 1);
  51013. }
  51014. }
  51015. if (!camera) {
  51016. return;
  51017. }
  51018. camera.detachPostProcess(this);
  51019. var index = camera._postProcesses.indexOf(this);
  51020. if (index === 0 && camera._postProcesses.length > 0) {
  51021. this._camera._postProcesses[0].markTextureDirty();
  51022. }
  51023. this.onActivateObservable.clear();
  51024. this.onAfterRenderObservable.clear();
  51025. this.onApplyObservable.clear();
  51026. this.onBeforeRenderObservable.clear();
  51027. this.onSizeChangedObservable.clear();
  51028. };
  51029. return PostProcess;
  51030. }());
  51031. BABYLON.PostProcess = PostProcess;
  51032. })(BABYLON || (BABYLON = {}));
  51033. //# sourceMappingURL=babylon.postProcess.js.map
  51034. var BABYLON;
  51035. (function (BABYLON) {
  51036. var PassPostProcess = /** @class */ (function (_super) {
  51037. __extends(PassPostProcess, _super);
  51038. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  51039. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51040. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  51041. }
  51042. return PassPostProcess;
  51043. }(BABYLON.PostProcess));
  51044. BABYLON.PassPostProcess = PassPostProcess;
  51045. })(BABYLON || (BABYLON = {}));
  51046. //# sourceMappingURL=babylon.passPostProcess.js.map
  51047. var BABYLON;
  51048. (function (BABYLON) {
  51049. var ShadowGenerator = /** @class */ (function () {
  51050. /**
  51051. * Creates a ShadowGenerator object.
  51052. * A ShadowGenerator is the required tool to use the shadows.
  51053. * Each light casting shadows needs to use its own ShadowGenerator.
  51054. * Required parameters :
  51055. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  51056. * - `light`: the light object generating the shadows.
  51057. * - `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.
  51058. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  51059. */
  51060. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  51061. // Members
  51062. this._bias = 0.00005;
  51063. this._blurBoxOffset = 1;
  51064. this._blurScale = 2;
  51065. this._blurKernel = 1;
  51066. this._useKernelBlur = false;
  51067. this._filter = ShadowGenerator.FILTER_NONE;
  51068. this._darkness = 0;
  51069. this._transparencyShadow = false;
  51070. /**
  51071. * Controls the extent to which the shadows fade out at the edge of the frustum
  51072. * Used only by directionals and spots
  51073. */
  51074. this.frustumEdgeFalloff = 0;
  51075. this.forceBackFacesOnly = false;
  51076. this._lightDirection = BABYLON.Vector3.Zero();
  51077. this._viewMatrix = BABYLON.Matrix.Zero();
  51078. this._projectionMatrix = BABYLON.Matrix.Zero();
  51079. this._transformMatrix = BABYLON.Matrix.Zero();
  51080. this._currentFaceIndex = 0;
  51081. this._currentFaceIndexCache = 0;
  51082. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  51083. this._mapSize = mapSize;
  51084. this._light = light;
  51085. this._scene = light.getScene();
  51086. light._shadowGenerator = this;
  51087. // Texture type fallback from float to int if not supported.
  51088. var caps = this._scene.getEngine().getCaps();
  51089. if (!useFullFloatFirst) {
  51090. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51091. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51092. }
  51093. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51094. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51095. }
  51096. else {
  51097. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51098. }
  51099. }
  51100. else {
  51101. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  51102. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  51103. }
  51104. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  51105. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  51106. }
  51107. else {
  51108. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  51109. }
  51110. }
  51111. this._initializeGenerator();
  51112. }
  51113. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  51114. // Static
  51115. get: function () {
  51116. return ShadowGenerator._FILTER_NONE;
  51117. },
  51118. enumerable: true,
  51119. configurable: true
  51120. });
  51121. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  51122. get: function () {
  51123. return ShadowGenerator._FILTER_POISSONSAMPLING;
  51124. },
  51125. enumerable: true,
  51126. configurable: true
  51127. });
  51128. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  51129. get: function () {
  51130. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  51131. },
  51132. enumerable: true,
  51133. configurable: true
  51134. });
  51135. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  51136. get: function () {
  51137. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  51138. },
  51139. enumerable: true,
  51140. configurable: true
  51141. });
  51142. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  51143. get: function () {
  51144. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51145. },
  51146. enumerable: true,
  51147. configurable: true
  51148. });
  51149. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  51150. get: function () {
  51151. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51152. },
  51153. enumerable: true,
  51154. configurable: true
  51155. });
  51156. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  51157. get: function () {
  51158. return this._bias;
  51159. },
  51160. set: function (bias) {
  51161. this._bias = bias;
  51162. },
  51163. enumerable: true,
  51164. configurable: true
  51165. });
  51166. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  51167. get: function () {
  51168. return this._blurBoxOffset;
  51169. },
  51170. set: function (value) {
  51171. if (this._blurBoxOffset === value) {
  51172. return;
  51173. }
  51174. this._blurBoxOffset = value;
  51175. this._disposeBlurPostProcesses();
  51176. },
  51177. enumerable: true,
  51178. configurable: true
  51179. });
  51180. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  51181. get: function () {
  51182. return this._blurScale;
  51183. },
  51184. set: function (value) {
  51185. if (this._blurScale === value) {
  51186. return;
  51187. }
  51188. this._blurScale = value;
  51189. this._disposeBlurPostProcesses();
  51190. },
  51191. enumerable: true,
  51192. configurable: true
  51193. });
  51194. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  51195. get: function () {
  51196. return this._blurKernel;
  51197. },
  51198. set: function (value) {
  51199. if (this._blurKernel === value) {
  51200. return;
  51201. }
  51202. this._blurKernel = value;
  51203. this._disposeBlurPostProcesses();
  51204. },
  51205. enumerable: true,
  51206. configurable: true
  51207. });
  51208. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  51209. get: function () {
  51210. return this._useKernelBlur;
  51211. },
  51212. set: function (value) {
  51213. if (this._useKernelBlur === value) {
  51214. return;
  51215. }
  51216. this._useKernelBlur = value;
  51217. this._disposeBlurPostProcesses();
  51218. },
  51219. enumerable: true,
  51220. configurable: true
  51221. });
  51222. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  51223. get: function () {
  51224. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  51225. },
  51226. set: function (value) {
  51227. this._depthScale = value;
  51228. },
  51229. enumerable: true,
  51230. configurable: true
  51231. });
  51232. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  51233. get: function () {
  51234. return this._filter;
  51235. },
  51236. set: function (value) {
  51237. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  51238. if (this._light.needCube()) {
  51239. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51240. this.useExponentialShadowMap = true;
  51241. return;
  51242. }
  51243. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51244. this.useCloseExponentialShadowMap = true;
  51245. return;
  51246. }
  51247. }
  51248. if (this._filter === value) {
  51249. return;
  51250. }
  51251. this._filter = value;
  51252. this._disposeBlurPostProcesses();
  51253. this._applyFilterValues();
  51254. this._light._markMeshesAsLightDirty();
  51255. },
  51256. enumerable: true,
  51257. configurable: true
  51258. });
  51259. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  51260. get: function () {
  51261. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  51262. },
  51263. set: function (value) {
  51264. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  51265. return;
  51266. }
  51267. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  51268. },
  51269. enumerable: true,
  51270. configurable: true
  51271. });
  51272. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  51273. get: function () {
  51274. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51275. return this.useExponentialShadowMap;
  51276. },
  51277. set: function (value) {
  51278. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  51279. this.useExponentialShadowMap = value;
  51280. },
  51281. enumerable: true,
  51282. configurable: true
  51283. });
  51284. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  51285. get: function () {
  51286. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51287. return this.useBlurExponentialShadowMap;
  51288. },
  51289. set: function (value) {
  51290. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  51291. this.useBlurExponentialShadowMap = value;
  51292. },
  51293. enumerable: true,
  51294. configurable: true
  51295. });
  51296. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  51297. get: function () {
  51298. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  51299. },
  51300. set: function (value) {
  51301. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  51302. return;
  51303. }
  51304. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51305. },
  51306. enumerable: true,
  51307. configurable: true
  51308. });
  51309. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  51310. get: function () {
  51311. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  51312. },
  51313. set: function (value) {
  51314. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  51315. return;
  51316. }
  51317. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51318. },
  51319. enumerable: true,
  51320. configurable: true
  51321. });
  51322. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  51323. get: function () {
  51324. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  51325. },
  51326. set: function (value) {
  51327. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  51328. return;
  51329. }
  51330. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51331. },
  51332. enumerable: true,
  51333. configurable: true
  51334. });
  51335. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  51336. get: function () {
  51337. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  51338. },
  51339. set: function (value) {
  51340. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  51341. return;
  51342. }
  51343. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  51344. },
  51345. enumerable: true,
  51346. configurable: true
  51347. });
  51348. /**
  51349. * Returns the darkness value (float).
  51350. */
  51351. ShadowGenerator.prototype.getDarkness = function () {
  51352. return this._darkness;
  51353. };
  51354. /**
  51355. * Sets the ShadowGenerator darkness value (float <= 1.0).
  51356. * Returns the ShadowGenerator.
  51357. */
  51358. ShadowGenerator.prototype.setDarkness = function (darkness) {
  51359. if (darkness >= 1.0)
  51360. this._darkness = 1.0;
  51361. else if (darkness <= 0.0)
  51362. this._darkness = 0.0;
  51363. else
  51364. this._darkness = darkness;
  51365. return this;
  51366. };
  51367. /**
  51368. * Sets the ability to have transparent shadow (boolean).
  51369. * Returns the ShadowGenerator.
  51370. */
  51371. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  51372. this._transparencyShadow = hasShadow;
  51373. return this;
  51374. };
  51375. /**
  51376. * Returns a RenderTargetTexture object : the shadow map texture.
  51377. */
  51378. ShadowGenerator.prototype.getShadowMap = function () {
  51379. return this._shadowMap;
  51380. };
  51381. /**
  51382. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  51383. */
  51384. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  51385. if (this._shadowMap2) {
  51386. return this._shadowMap2;
  51387. }
  51388. return this._shadowMap;
  51389. };
  51390. /**
  51391. * Helper function to add a mesh and its descendants to the list of shadow casters
  51392. * @param mesh Mesh to add
  51393. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  51394. */
  51395. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  51396. if (includeDescendants === void 0) { includeDescendants = true; }
  51397. if (!this._shadowMap) {
  51398. return this;
  51399. }
  51400. if (!this._shadowMap.renderList) {
  51401. this._shadowMap.renderList = [];
  51402. }
  51403. this._shadowMap.renderList.push(mesh);
  51404. if (includeDescendants) {
  51405. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  51406. }
  51407. return this;
  51408. var _a;
  51409. };
  51410. /**
  51411. * Helper function to remove a mesh and its descendants from the list of shadow casters
  51412. * @param mesh Mesh to remove
  51413. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  51414. */
  51415. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  51416. if (includeDescendants === void 0) { includeDescendants = true; }
  51417. if (!this._shadowMap || !this._shadowMap.renderList) {
  51418. return this;
  51419. }
  51420. var index = this._shadowMap.renderList.indexOf(mesh);
  51421. if (index !== -1) {
  51422. this._shadowMap.renderList.splice(index, 1);
  51423. }
  51424. if (includeDescendants) {
  51425. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  51426. var child = _a[_i];
  51427. this.removeShadowCaster(child);
  51428. }
  51429. }
  51430. return this;
  51431. };
  51432. /**
  51433. * Returns the associated light object.
  51434. */
  51435. ShadowGenerator.prototype.getLight = function () {
  51436. return this._light;
  51437. };
  51438. ShadowGenerator.prototype._initializeGenerator = function () {
  51439. this._light._markMeshesAsLightDirty();
  51440. this._initializeShadowMap();
  51441. };
  51442. ShadowGenerator.prototype._initializeShadowMap = function () {
  51443. var _this = this;
  51444. // Render target
  51445. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  51446. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51447. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51448. this._shadowMap.anisotropicFilteringLevel = 1;
  51449. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51450. this._shadowMap.renderParticles = false;
  51451. this._shadowMap.ignoreCameraViewport = true;
  51452. // Record Face Index before render.
  51453. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  51454. _this._currentFaceIndex = faceIndex;
  51455. });
  51456. // Custom render function.
  51457. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  51458. // Blur if required afer render.
  51459. this._shadowMap.onAfterUnbindObservable.add(function () {
  51460. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  51461. return;
  51462. }
  51463. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  51464. _this._initializeBlurRTTAndPostProcesses();
  51465. }
  51466. var shadowMap = _this.getShadowMapForRendering();
  51467. if (shadowMap) {
  51468. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  51469. }
  51470. });
  51471. // Clear according to the chosen filter.
  51472. this._shadowMap.onClearObservable.add(function (engine) {
  51473. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  51474. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  51475. }
  51476. else {
  51477. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  51478. }
  51479. });
  51480. };
  51481. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  51482. var _this = this;
  51483. var engine = this._scene.getEngine();
  51484. var targetSize = this._mapSize / this.blurScale;
  51485. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  51486. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  51487. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51488. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51489. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51490. }
  51491. if (this.useKernelBlur) {
  51492. 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);
  51493. this._kernelBlurXPostprocess.width = targetSize;
  51494. this._kernelBlurXPostprocess.height = targetSize;
  51495. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  51496. effect.setTexture("textureSampler", _this._shadowMap);
  51497. });
  51498. 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);
  51499. this._kernelBlurXPostprocess.autoClear = false;
  51500. this._kernelBlurYPostprocess.autoClear = false;
  51501. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51502. this._kernelBlurXPostprocess.packedFloat = true;
  51503. this._kernelBlurYPostprocess.packedFloat = true;
  51504. }
  51505. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  51506. }
  51507. else {
  51508. 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);
  51509. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  51510. effect.setFloat2("screenSize", targetSize, targetSize);
  51511. effect.setTexture("textureSampler", _this._shadowMap);
  51512. });
  51513. this._boxBlurPostprocess.autoClear = false;
  51514. this._blurPostProcesses = [this._boxBlurPostprocess];
  51515. }
  51516. };
  51517. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  51518. var index;
  51519. var engine = this._scene.getEngine();
  51520. if (depthOnlySubMeshes.length) {
  51521. engine.setColorWrite(false);
  51522. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  51523. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  51524. }
  51525. engine.setColorWrite(true);
  51526. }
  51527. for (index = 0; index < opaqueSubMeshes.length; index++) {
  51528. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  51529. }
  51530. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  51531. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  51532. }
  51533. if (this._transparencyShadow) {
  51534. for (index = 0; index < transparentSubMeshes.length; index++) {
  51535. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  51536. }
  51537. }
  51538. };
  51539. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  51540. var _this = this;
  51541. var mesh = subMesh.getRenderingMesh();
  51542. var scene = this._scene;
  51543. var engine = scene.getEngine();
  51544. var material = subMesh.getMaterial();
  51545. if (!material) {
  51546. return;
  51547. }
  51548. // Culling
  51549. engine.setState(material.backFaceCulling);
  51550. // Managing instances
  51551. var batch = mesh._getInstancesRenderList(subMesh._id);
  51552. if (batch.mustReturn) {
  51553. return;
  51554. }
  51555. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  51556. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  51557. engine.enableEffect(this._effect);
  51558. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  51559. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  51560. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  51561. this._effect.setVector3("lightPosition", this.getLight().position);
  51562. if (scene.activeCamera) {
  51563. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  51564. }
  51565. // Alpha test
  51566. if (material && material.needAlphaTesting()) {
  51567. var alphaTexture = material.getAlphaTestTexture();
  51568. if (alphaTexture) {
  51569. this._effect.setTexture("diffuseSampler", alphaTexture);
  51570. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  51571. }
  51572. }
  51573. // Bones
  51574. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51575. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  51576. }
  51577. if (this.forceBackFacesOnly) {
  51578. engine.setState(true, 0, false, true);
  51579. }
  51580. // Draw
  51581. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  51582. if (this.forceBackFacesOnly) {
  51583. engine.setState(true, 0, false, false);
  51584. }
  51585. }
  51586. else {
  51587. // Need to reset refresh rate of the shadowMap
  51588. if (this._shadowMap) {
  51589. this._shadowMap.resetRefreshCounter();
  51590. }
  51591. }
  51592. };
  51593. ShadowGenerator.prototype._applyFilterValues = function () {
  51594. if (!this._shadowMap) {
  51595. return;
  51596. }
  51597. if (this.filter === ShadowGenerator.FILTER_NONE) {
  51598. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  51599. }
  51600. else {
  51601. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51602. }
  51603. };
  51604. /**
  51605. * Force shader compilation including textures ready check
  51606. */
  51607. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  51608. var _this = this;
  51609. var shadowMap = this.getShadowMap();
  51610. if (!shadowMap) {
  51611. return;
  51612. }
  51613. var subMeshes = new Array();
  51614. var currentIndex = 0;
  51615. var renderList = shadowMap.renderList;
  51616. if (!renderList) {
  51617. return;
  51618. }
  51619. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  51620. var mesh = renderList_1[_i];
  51621. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  51622. }
  51623. var checkReady = function () {
  51624. if (!_this._scene || !_this._scene.getEngine()) {
  51625. return;
  51626. }
  51627. while (_this.isReady(subMeshes[currentIndex], options ? options.useInstances : false)) {
  51628. currentIndex++;
  51629. if (currentIndex >= subMeshes.length) {
  51630. if (onCompiled) {
  51631. onCompiled(_this);
  51632. }
  51633. return;
  51634. }
  51635. }
  51636. setTimeout(checkReady, 16);
  51637. };
  51638. if (subMeshes.length > 0) {
  51639. checkReady();
  51640. }
  51641. };
  51642. /**
  51643. * Boolean : true when the ShadowGenerator is finally computed.
  51644. */
  51645. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  51646. var defines = [];
  51647. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  51648. defines.push("#define FLOAT");
  51649. }
  51650. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51651. defines.push("#define ESM");
  51652. }
  51653. var attribs = [BABYLON.VertexBuffer.PositionKind];
  51654. var mesh = subMesh.getMesh();
  51655. var material = subMesh.getMaterial();
  51656. // Alpha test
  51657. if (material && material.needAlphaTesting()) {
  51658. var alphaTexture = material.getAlphaTestTexture();
  51659. if (alphaTexture) {
  51660. defines.push("#define ALPHATEST");
  51661. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51662. attribs.push(BABYLON.VertexBuffer.UVKind);
  51663. defines.push("#define UV1");
  51664. }
  51665. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51666. if (alphaTexture.coordinatesIndex === 1) {
  51667. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  51668. defines.push("#define UV2");
  51669. }
  51670. }
  51671. }
  51672. }
  51673. // Bones
  51674. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51675. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  51676. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  51677. if (mesh.numBoneInfluencers > 4) {
  51678. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  51679. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  51680. }
  51681. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  51682. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  51683. }
  51684. else {
  51685. defines.push("#define NUM_BONE_INFLUENCERS 0");
  51686. }
  51687. // Instances
  51688. if (useInstances) {
  51689. defines.push("#define INSTANCES");
  51690. attribs.push("world0");
  51691. attribs.push("world1");
  51692. attribs.push("world2");
  51693. attribs.push("world3");
  51694. }
  51695. // Get correct effect
  51696. var join = defines.join("\n");
  51697. if (this._cachedDefines !== join) {
  51698. this._cachedDefines = join;
  51699. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  51700. }
  51701. return this._effect.isReady();
  51702. };
  51703. /**
  51704. * This creates the defines related to the standard BJS materials.
  51705. */
  51706. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  51707. var scene = this._scene;
  51708. var light = this._light;
  51709. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51710. return;
  51711. }
  51712. defines["SHADOW" + lightIndex] = true;
  51713. if (this.usePoissonSampling) {
  51714. defines["SHADOWPCF" + lightIndex] = true;
  51715. }
  51716. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  51717. defines["SHADOWESM" + lightIndex] = true;
  51718. }
  51719. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  51720. defines["SHADOWCLOSEESM" + lightIndex] = true;
  51721. }
  51722. if (light.needCube()) {
  51723. defines["SHADOWCUBE" + lightIndex] = true;
  51724. }
  51725. };
  51726. /**
  51727. * This binds shadow lights related to the standard BJS materials.
  51728. * It implies the unifroms available on the materials are the standard BJS ones.
  51729. */
  51730. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  51731. var light = this._light;
  51732. var scene = this._scene;
  51733. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  51734. return;
  51735. }
  51736. var camera = scene.activeCamera;
  51737. if (!camera) {
  51738. return;
  51739. }
  51740. var shadowMap = this.getShadowMap();
  51741. if (!shadowMap) {
  51742. return;
  51743. }
  51744. if (!light.needCube()) {
  51745. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  51746. }
  51747. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  51748. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  51749. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  51750. };
  51751. // Methods
  51752. /**
  51753. * Returns a Matrix object : the updated transformation matrix.
  51754. */
  51755. ShadowGenerator.prototype.getTransformMatrix = function () {
  51756. var scene = this._scene;
  51757. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  51758. return this._transformMatrix;
  51759. }
  51760. this._currentRenderID = scene.getRenderId();
  51761. this._currentFaceIndexCache = this._currentFaceIndex;
  51762. var lightPosition = this._light.position;
  51763. if (this._light.computeTransformedInformation()) {
  51764. lightPosition = this._light.transformedPosition;
  51765. }
  51766. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  51767. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  51768. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  51769. }
  51770. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  51771. this._cachedPosition = lightPosition.clone();
  51772. this._cachedDirection = this._lightDirection.clone();
  51773. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  51774. var shadowMap = this.getShadowMap();
  51775. if (shadowMap) {
  51776. var renderList = shadowMap.renderList;
  51777. if (renderList) {
  51778. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  51779. }
  51780. }
  51781. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  51782. }
  51783. return this._transformMatrix;
  51784. };
  51785. ShadowGenerator.prototype.recreateShadowMap = function () {
  51786. var shadowMap = this._shadowMap;
  51787. if (!shadowMap) {
  51788. return;
  51789. }
  51790. // Track render list.
  51791. var renderList = shadowMap.renderList;
  51792. // Clean up existing data.
  51793. this._disposeRTTandPostProcesses();
  51794. // Reinitializes.
  51795. this._initializeGenerator();
  51796. // Reaffect the filter to ensure a correct fallback if necessary.
  51797. this.filter = this.filter;
  51798. // Reaffect the filter.
  51799. this._applyFilterValues();
  51800. // Reaffect Render List.
  51801. this._shadowMap.renderList = renderList;
  51802. };
  51803. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  51804. if (this._shadowMap2) {
  51805. this._shadowMap2.dispose();
  51806. this._shadowMap2 = null;
  51807. }
  51808. if (this._downSamplePostprocess) {
  51809. this._downSamplePostprocess.dispose();
  51810. this._downSamplePostprocess = null;
  51811. }
  51812. if (this._boxBlurPostprocess) {
  51813. this._boxBlurPostprocess.dispose();
  51814. this._boxBlurPostprocess = null;
  51815. }
  51816. if (this._kernelBlurXPostprocess) {
  51817. this._kernelBlurXPostprocess.dispose();
  51818. this._kernelBlurXPostprocess = null;
  51819. }
  51820. if (this._kernelBlurYPostprocess) {
  51821. this._kernelBlurYPostprocess.dispose();
  51822. this._kernelBlurYPostprocess = null;
  51823. }
  51824. this._blurPostProcesses = [];
  51825. };
  51826. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  51827. if (this._shadowMap) {
  51828. this._shadowMap.dispose();
  51829. this._shadowMap = null;
  51830. }
  51831. this._disposeBlurPostProcesses();
  51832. };
  51833. /**
  51834. * Disposes the ShadowGenerator.
  51835. * Returns nothing.
  51836. */
  51837. ShadowGenerator.prototype.dispose = function () {
  51838. this._disposeRTTandPostProcesses();
  51839. if (this._light) {
  51840. this._light._shadowGenerator = null;
  51841. this._light._markMeshesAsLightDirty();
  51842. }
  51843. };
  51844. /**
  51845. * Serializes the ShadowGenerator and returns a serializationObject.
  51846. */
  51847. ShadowGenerator.prototype.serialize = function () {
  51848. var serializationObject = {};
  51849. var shadowMap = this.getShadowMap();
  51850. if (!shadowMap) {
  51851. return serializationObject;
  51852. }
  51853. serializationObject.lightId = this._light.id;
  51854. serializationObject.mapSize = shadowMap.getRenderSize();
  51855. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  51856. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  51857. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51858. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  51859. serializationObject.usePoissonSampling = this.usePoissonSampling;
  51860. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  51861. serializationObject.depthScale = this.depthScale;
  51862. serializationObject.darkness = this.getDarkness();
  51863. serializationObject.blurBoxOffset = this.blurBoxOffset;
  51864. serializationObject.blurKernel = this.blurKernel;
  51865. serializationObject.blurScale = this.blurScale;
  51866. serializationObject.useKernelBlur = this.useKernelBlur;
  51867. serializationObject.transparencyShadow = this._transparencyShadow;
  51868. serializationObject.renderList = [];
  51869. if (shadowMap.renderList) {
  51870. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  51871. var mesh = shadowMap.renderList[meshIndex];
  51872. serializationObject.renderList.push(mesh.id);
  51873. }
  51874. }
  51875. return serializationObject;
  51876. };
  51877. /**
  51878. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  51879. */
  51880. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  51881. //casting to point light, as light is missing the position attr and typescript complains.
  51882. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  51883. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  51884. var shadowMap = shadowGenerator.getShadowMap();
  51885. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  51886. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  51887. meshes.forEach(function (mesh) {
  51888. if (!shadowMap) {
  51889. return;
  51890. }
  51891. if (!shadowMap.renderList) {
  51892. shadowMap.renderList = [];
  51893. }
  51894. shadowMap.renderList.push(mesh);
  51895. });
  51896. }
  51897. if (parsedShadowGenerator.usePoissonSampling) {
  51898. shadowGenerator.usePoissonSampling = true;
  51899. }
  51900. else if (parsedShadowGenerator.useExponentialShadowMap) {
  51901. shadowGenerator.useExponentialShadowMap = true;
  51902. }
  51903. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  51904. shadowGenerator.useBlurExponentialShadowMap = true;
  51905. }
  51906. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  51907. shadowGenerator.useCloseExponentialShadowMap = true;
  51908. }
  51909. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  51910. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  51911. }
  51912. else if (parsedShadowGenerator.useVarianceShadowMap) {
  51913. shadowGenerator.useExponentialShadowMap = true;
  51914. }
  51915. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  51916. shadowGenerator.useBlurExponentialShadowMap = true;
  51917. }
  51918. if (parsedShadowGenerator.depthScale) {
  51919. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  51920. }
  51921. if (parsedShadowGenerator.blurScale) {
  51922. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  51923. }
  51924. if (parsedShadowGenerator.blurBoxOffset) {
  51925. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  51926. }
  51927. if (parsedShadowGenerator.useKernelBlur) {
  51928. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  51929. }
  51930. if (parsedShadowGenerator.blurKernel) {
  51931. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  51932. }
  51933. if (parsedShadowGenerator.bias !== undefined) {
  51934. shadowGenerator.bias = parsedShadowGenerator.bias;
  51935. }
  51936. if (parsedShadowGenerator.darkness) {
  51937. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  51938. }
  51939. if (parsedShadowGenerator.transparencyShadow) {
  51940. shadowGenerator.setTransparencyShadow(true);
  51941. }
  51942. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  51943. return shadowGenerator;
  51944. };
  51945. ShadowGenerator._FILTER_NONE = 0;
  51946. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  51947. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  51948. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  51949. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  51950. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  51951. return ShadowGenerator;
  51952. }());
  51953. BABYLON.ShadowGenerator = ShadowGenerator;
  51954. })(BABYLON || (BABYLON = {}));
  51955. //# sourceMappingURL=babylon.shadowGenerator.js.map
  51956. var BABYLON;
  51957. (function (BABYLON) {
  51958. var DefaultLoadingScreen = /** @class */ (function () {
  51959. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  51960. if (_loadingText === void 0) { _loadingText = ""; }
  51961. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  51962. var _this = this;
  51963. this._renderingCanvas = _renderingCanvas;
  51964. this._loadingText = _loadingText;
  51965. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  51966. // Resize
  51967. this._resizeLoadingUI = function () {
  51968. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  51969. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  51970. if (!_this._loadingDiv) {
  51971. return;
  51972. }
  51973. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  51974. _this._loadingDiv.style.left = canvasRect.left + "px";
  51975. _this._loadingDiv.style.top = canvasRect.top + "px";
  51976. _this._loadingDiv.style.width = canvasRect.width + "px";
  51977. _this._loadingDiv.style.height = canvasRect.height + "px";
  51978. };
  51979. }
  51980. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  51981. if (this._loadingDiv) {
  51982. // Do not add a loading screen if there is already one
  51983. return;
  51984. }
  51985. this._loadingDiv = document.createElement("div");
  51986. this._loadingDiv.id = "babylonjsLoadingDiv";
  51987. this._loadingDiv.style.opacity = "0";
  51988. this._loadingDiv.style.transition = "opacity 1.5s ease";
  51989. this._loadingDiv.style.pointerEvents = "none";
  51990. // Loading text
  51991. this._loadingTextDiv = document.createElement("div");
  51992. this._loadingTextDiv.style.position = "absolute";
  51993. this._loadingTextDiv.style.left = "0";
  51994. this._loadingTextDiv.style.top = "50%";
  51995. this._loadingTextDiv.style.marginTop = "80px";
  51996. this._loadingTextDiv.style.width = "100%";
  51997. this._loadingTextDiv.style.height = "20px";
  51998. this._loadingTextDiv.style.fontFamily = "Arial";
  51999. this._loadingTextDiv.style.fontSize = "14px";
  52000. this._loadingTextDiv.style.color = "white";
  52001. this._loadingTextDiv.style.textAlign = "center";
  52002. this._loadingTextDiv.innerHTML = "Loading";
  52003. this._loadingDiv.appendChild(this._loadingTextDiv);
  52004. //set the predefined text
  52005. this._loadingTextDiv.innerHTML = this._loadingText;
  52006. // Generating keyframes
  52007. var style = document.createElement('style');
  52008. style.type = 'text/css';
  52009. 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 }";
  52010. style.innerHTML = keyFrames;
  52011. document.getElementsByTagName('head')[0].appendChild(style);
  52012. // Loading img
  52013. var imgBack = new Image();
  52014. 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";
  52015. imgBack.style.position = "absolute";
  52016. imgBack.style.left = "50%";
  52017. imgBack.style.top = "50%";
  52018. imgBack.style.marginLeft = "-60px";
  52019. imgBack.style.marginTop = "-60px";
  52020. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  52021. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  52022. imgBack.style.transformOrigin = "50% 50%";
  52023. imgBack.style.webkitTransformOrigin = "50% 50%";
  52024. this._loadingDiv.appendChild(imgBack);
  52025. this._resizeLoadingUI();
  52026. window.addEventListener("resize", this._resizeLoadingUI);
  52027. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52028. document.body.appendChild(this._loadingDiv);
  52029. this._loadingDiv.style.opacity = "1";
  52030. };
  52031. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  52032. var _this = this;
  52033. if (!this._loadingDiv) {
  52034. return;
  52035. }
  52036. var onTransitionEnd = function () {
  52037. if (!_this._loadingDiv) {
  52038. return;
  52039. }
  52040. document.body.removeChild(_this._loadingDiv);
  52041. window.removeEventListener("resize", _this._resizeLoadingUI);
  52042. _this._loadingDiv = null;
  52043. };
  52044. this._loadingDiv.style.opacity = "0";
  52045. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  52046. };
  52047. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  52048. set: function (text) {
  52049. this._loadingText = text;
  52050. if (this._loadingTextDiv) {
  52051. this._loadingTextDiv.innerHTML = this._loadingText;
  52052. }
  52053. },
  52054. enumerable: true,
  52055. configurable: true
  52056. });
  52057. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  52058. get: function () {
  52059. return this._loadingDivBackgroundColor;
  52060. },
  52061. set: function (color) {
  52062. this._loadingDivBackgroundColor = color;
  52063. if (!this._loadingDiv) {
  52064. return;
  52065. }
  52066. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  52067. },
  52068. enumerable: true,
  52069. configurable: true
  52070. });
  52071. return DefaultLoadingScreen;
  52072. }());
  52073. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  52074. })(BABYLON || (BABYLON = {}));
  52075. //# sourceMappingURL=babylon.loadingScreen.js.map
  52076. var BABYLON;
  52077. (function (BABYLON) {
  52078. var SceneLoader = /** @class */ (function () {
  52079. function SceneLoader() {
  52080. }
  52081. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  52082. get: function () {
  52083. return 0;
  52084. },
  52085. enumerable: true,
  52086. configurable: true
  52087. });
  52088. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  52089. get: function () {
  52090. return 1;
  52091. },
  52092. enumerable: true,
  52093. configurable: true
  52094. });
  52095. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  52096. get: function () {
  52097. return 2;
  52098. },
  52099. enumerable: true,
  52100. configurable: true
  52101. });
  52102. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  52103. get: function () {
  52104. return 3;
  52105. },
  52106. enumerable: true,
  52107. configurable: true
  52108. });
  52109. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  52110. get: function () {
  52111. return SceneLoader._ForceFullSceneLoadingForIncremental;
  52112. },
  52113. set: function (value) {
  52114. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  52115. },
  52116. enumerable: true,
  52117. configurable: true
  52118. });
  52119. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  52120. get: function () {
  52121. return SceneLoader._ShowLoadingScreen;
  52122. },
  52123. set: function (value) {
  52124. SceneLoader._ShowLoadingScreen = value;
  52125. },
  52126. enumerable: true,
  52127. configurable: true
  52128. });
  52129. Object.defineProperty(SceneLoader, "loggingLevel", {
  52130. get: function () {
  52131. return SceneLoader._loggingLevel;
  52132. },
  52133. set: function (value) {
  52134. SceneLoader._loggingLevel = value;
  52135. },
  52136. enumerable: true,
  52137. configurable: true
  52138. });
  52139. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  52140. get: function () {
  52141. return SceneLoader._CleanBoneMatrixWeights;
  52142. },
  52143. set: function (value) {
  52144. SceneLoader._CleanBoneMatrixWeights = value;
  52145. },
  52146. enumerable: true,
  52147. configurable: true
  52148. });
  52149. SceneLoader._getDefaultPlugin = function () {
  52150. return SceneLoader._registeredPlugins[".babylon"];
  52151. };
  52152. SceneLoader._getPluginForExtension = function (extension) {
  52153. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  52154. if (registeredPlugin) {
  52155. return registeredPlugin;
  52156. }
  52157. return SceneLoader._getDefaultPlugin();
  52158. };
  52159. SceneLoader._getPluginForDirectLoad = function (data) {
  52160. for (var extension in SceneLoader._registeredPlugins) {
  52161. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  52162. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  52163. return SceneLoader._registeredPlugins[extension];
  52164. }
  52165. }
  52166. return SceneLoader._getDefaultPlugin();
  52167. };
  52168. SceneLoader._getPluginForFilename = function (sceneFilename) {
  52169. if (sceneFilename.name) {
  52170. sceneFilename = sceneFilename.name;
  52171. }
  52172. var dotPosition = sceneFilename.lastIndexOf(".");
  52173. var queryStringPosition = sceneFilename.indexOf("?");
  52174. if (queryStringPosition === -1) {
  52175. queryStringPosition = sceneFilename.length;
  52176. }
  52177. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  52178. return SceneLoader._getPluginForExtension(extension);
  52179. };
  52180. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  52181. SceneLoader._getDirectLoad = function (sceneFilename) {
  52182. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  52183. return sceneFilename.substr(5);
  52184. }
  52185. return null;
  52186. };
  52187. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52188. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  52189. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  52190. var plugin = registeredPlugin.plugin;
  52191. var useArrayBuffer = registeredPlugin.isBinary;
  52192. var database;
  52193. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  52194. var dataCallback = function (data) {
  52195. if (scene.isDisposed) {
  52196. onError("Scene has been disposed");
  52197. return;
  52198. }
  52199. scene.database = database;
  52200. try {
  52201. onSuccess(plugin, data);
  52202. }
  52203. catch (e) {
  52204. onError(null, e);
  52205. }
  52206. };
  52207. var manifestChecked = function (success) {
  52208. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  52209. if (request) {
  52210. onError(request.status + " " + request.statusText);
  52211. }
  52212. });
  52213. };
  52214. if (directLoad) {
  52215. dataCallback(directLoad);
  52216. return;
  52217. }
  52218. if (rootUrl.indexOf("file:") === -1) {
  52219. if (scene.getEngine().enableOfflineSupport) {
  52220. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  52221. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  52222. }
  52223. else {
  52224. manifestChecked(true);
  52225. }
  52226. }
  52227. else {
  52228. var fileOrString = sceneFilename;
  52229. if (fileOrString.name) {
  52230. BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  52231. }
  52232. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  52233. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  52234. }
  52235. else {
  52236. onError("Unable to find file named " + sceneFilename);
  52237. return;
  52238. }
  52239. }
  52240. };
  52241. // Public functions
  52242. SceneLoader.GetPluginForExtension = function (extension) {
  52243. return SceneLoader._getPluginForExtension(extension).plugin;
  52244. };
  52245. SceneLoader.RegisterPlugin = function (plugin) {
  52246. if (typeof plugin.extensions === "string") {
  52247. var extension = plugin.extensions;
  52248. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52249. plugin: plugin,
  52250. isBinary: false
  52251. };
  52252. }
  52253. else {
  52254. var extensions = plugin.extensions;
  52255. Object.keys(extensions).forEach(function (extension) {
  52256. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  52257. plugin: plugin,
  52258. isBinary: extensions[extension].isBinary
  52259. };
  52260. });
  52261. }
  52262. };
  52263. /**
  52264. * Import meshes into a scene
  52265. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  52266. * @param rootUrl a string that defines the root url for scene and resources
  52267. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52268. * @param scene the instance of BABYLON.Scene to append to
  52269. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  52270. * @param onProgress a callback with a progress event for each file being loaded
  52271. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52272. */
  52273. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52274. if (onSuccess === void 0) { onSuccess = null; }
  52275. if (onProgress === void 0) { onProgress = null; }
  52276. if (onError === void 0) { onError = null; }
  52277. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52278. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52279. return;
  52280. }
  52281. var loadingToken = {};
  52282. scene._addPendingData(loadingToken);
  52283. var errorHandler = function (message, exception) {
  52284. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52285. if (onError) {
  52286. onError(scene, errorMessage, exception);
  52287. }
  52288. else {
  52289. BABYLON.Tools.Error(errorMessage);
  52290. // should the exception be thrown?
  52291. }
  52292. scene._removePendingData(loadingToken);
  52293. };
  52294. var progressHandler = function (event) {
  52295. if (onProgress) {
  52296. onProgress(event);
  52297. }
  52298. };
  52299. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52300. if (plugin.importMesh) {
  52301. var syncedPlugin = plugin;
  52302. var meshes = new Array();
  52303. var particleSystems = new Array();
  52304. var skeletons = new Array();
  52305. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  52306. return;
  52307. }
  52308. if (onSuccess) {
  52309. // wrap onSuccess with try-catch to know if something went wrong.
  52310. try {
  52311. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52312. onSuccess(meshes, particleSystems, skeletons);
  52313. scene._removePendingData(loadingToken);
  52314. }
  52315. catch (e) {
  52316. var message = 'Error in onSuccess callback.';
  52317. errorHandler(message, e);
  52318. }
  52319. }
  52320. }
  52321. else {
  52322. var asyncedPlugin = plugin;
  52323. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  52324. if (onSuccess) {
  52325. try {
  52326. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  52327. onSuccess(meshes, particleSystems, skeletons);
  52328. scene._removePendingData(loadingToken);
  52329. }
  52330. catch (e) {
  52331. var message = 'Error in onSuccess callback.';
  52332. errorHandler(message, e);
  52333. }
  52334. }
  52335. }, progressHandler, errorHandler);
  52336. }
  52337. }, progressHandler, errorHandler, pluginExtension);
  52338. };
  52339. /**
  52340. * Load a scene
  52341. * @param rootUrl a string that defines the root url for scene and resources
  52342. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52343. * @param engine is the instance of BABYLON.Engine to use to create the scene
  52344. * @param onSuccess a callback with the scene when import succeeds
  52345. * @param onProgress a callback with a progress event for each file being loaded
  52346. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52347. */
  52348. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  52349. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  52350. };
  52351. /**
  52352. * Append a scene
  52353. * @param rootUrl a string that defines the root url for scene and resources
  52354. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  52355. * @param scene is the instance of BABYLON.Scene to append to
  52356. * @param onSuccess a callback with the scene when import succeeds
  52357. * @param onProgress a callback with a progress event for each file being loaded
  52358. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  52359. */
  52360. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  52361. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  52362. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  52363. return;
  52364. }
  52365. if (SceneLoader.ShowLoadingScreen) {
  52366. scene.getEngine().displayLoadingUI();
  52367. }
  52368. var loadingToken = {};
  52369. scene._addPendingData(loadingToken);
  52370. var errorHandler = function (message, exception) {
  52371. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  52372. if (onError) {
  52373. onError(scene, errorMessage, exception);
  52374. }
  52375. else {
  52376. BABYLON.Tools.Error(errorMessage);
  52377. // should the exception be thrown?
  52378. }
  52379. scene._removePendingData(loadingToken);
  52380. scene.getEngine().hideLoadingUI();
  52381. };
  52382. var progressHandler = function (event) {
  52383. if (onProgress) {
  52384. onProgress(event);
  52385. }
  52386. };
  52387. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  52388. if (plugin.load) {
  52389. var syncedPlugin = plugin;
  52390. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  52391. return;
  52392. }
  52393. if (onSuccess) {
  52394. try {
  52395. onSuccess(scene);
  52396. }
  52397. catch (e) {
  52398. errorHandler("Error in onSuccess callback", e);
  52399. }
  52400. }
  52401. scene.loadingPluginName = plugin.name;
  52402. scene._removePendingData(loadingToken);
  52403. }
  52404. else {
  52405. var asyncedPlugin = plugin;
  52406. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  52407. if (onSuccess) {
  52408. onSuccess(scene);
  52409. }
  52410. scene.loadingPluginName = plugin.name;
  52411. scene._removePendingData(loadingToken);
  52412. }, progressHandler, errorHandler);
  52413. }
  52414. if (SceneLoader.ShowLoadingScreen) {
  52415. scene.executeWhenReady(function () {
  52416. scene.getEngine().hideLoadingUI();
  52417. });
  52418. }
  52419. }, progressHandler, errorHandler, pluginExtension);
  52420. };
  52421. // Flags
  52422. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  52423. SceneLoader._ShowLoadingScreen = true;
  52424. SceneLoader._CleanBoneMatrixWeights = false;
  52425. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  52426. // Members
  52427. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  52428. SceneLoader._registeredPlugins = {};
  52429. return SceneLoader;
  52430. }());
  52431. BABYLON.SceneLoader = SceneLoader;
  52432. ;
  52433. })(BABYLON || (BABYLON = {}));
  52434. //# sourceMappingURL=babylon.sceneLoader.js.map
  52435. var BABYLON;
  52436. (function (BABYLON) {
  52437. var Internals;
  52438. (function (Internals) {
  52439. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  52440. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52441. var parsedMaterial = parsedData.materials[index];
  52442. if (parsedMaterial.id === id) {
  52443. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52444. }
  52445. }
  52446. return null;
  52447. };
  52448. var isDescendantOf = function (mesh, names, hierarchyIds) {
  52449. for (var i in names) {
  52450. if (mesh.name === names[i]) {
  52451. hierarchyIds.push(mesh.id);
  52452. return true;
  52453. }
  52454. }
  52455. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  52456. hierarchyIds.push(mesh.id);
  52457. return true;
  52458. }
  52459. return false;
  52460. };
  52461. var logOperation = function (operation, producer) {
  52462. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  52463. };
  52464. BABYLON.SceneLoader.RegisterPlugin({
  52465. name: "babylon.js",
  52466. extensions: ".babylon",
  52467. canDirectLoad: function (data) {
  52468. if (data.indexOf("babylon") !== -1) {
  52469. return true;
  52470. }
  52471. return false;
  52472. },
  52473. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  52474. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52475. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52476. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52477. // and avoid problems with multiple concurrent .babylon loads.
  52478. var log = "importMesh has failed JSON parse";
  52479. try {
  52480. var parsedData = JSON.parse(data);
  52481. log = "";
  52482. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52483. if (!meshesNames) {
  52484. meshesNames = null;
  52485. }
  52486. else if (!Array.isArray(meshesNames)) {
  52487. meshesNames = [meshesNames];
  52488. }
  52489. var hierarchyIds = new Array();
  52490. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52491. var loadedSkeletonsIds = [];
  52492. var loadedMaterialsIds = [];
  52493. var index;
  52494. var cache;
  52495. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52496. var parsedMesh = parsedData.meshes[index];
  52497. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  52498. if (meshesNames !== null) {
  52499. // Remove found mesh name from list.
  52500. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  52501. }
  52502. //Geometry?
  52503. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  52504. //does the file contain geometries?
  52505. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  52506. //find the correct geometry and add it to the scene
  52507. var found = false;
  52508. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  52509. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  52510. return;
  52511. }
  52512. else {
  52513. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  52514. if (parsedGeometryData.id === parsedMesh.geometryId) {
  52515. switch (geometryType) {
  52516. case "boxes":
  52517. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  52518. break;
  52519. case "spheres":
  52520. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  52521. break;
  52522. case "cylinders":
  52523. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  52524. break;
  52525. case "toruses":
  52526. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  52527. break;
  52528. case "grounds":
  52529. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  52530. break;
  52531. case "planes":
  52532. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  52533. break;
  52534. case "torusKnots":
  52535. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  52536. break;
  52537. case "vertexData":
  52538. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  52539. break;
  52540. }
  52541. found = true;
  52542. }
  52543. });
  52544. }
  52545. });
  52546. if (found === false) {
  52547. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  52548. }
  52549. }
  52550. }
  52551. // Material ?
  52552. if (parsedMesh.materialId) {
  52553. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  52554. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52555. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  52556. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  52557. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  52558. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  52559. var subMatId = parsedMultiMaterial.materials[matIndex];
  52560. loadedMaterialsIds.push(subMatId);
  52561. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  52562. log += "\n\tMaterial " + mat.toString(fullDetails);
  52563. }
  52564. loadedMaterialsIds.push(parsedMultiMaterial.id);
  52565. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52566. materialFound = true;
  52567. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  52568. break;
  52569. }
  52570. }
  52571. }
  52572. if (materialFound === false) {
  52573. loadedMaterialsIds.push(parsedMesh.materialId);
  52574. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  52575. if (!mat) {
  52576. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  52577. }
  52578. else {
  52579. log += "\n\tMaterial " + mat.toString(fullDetails);
  52580. }
  52581. }
  52582. }
  52583. // Skeleton ?
  52584. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52585. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  52586. if (skeletonAlreadyLoaded === false) {
  52587. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  52588. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  52589. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  52590. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52591. skeletons.push(skeleton);
  52592. loadedSkeletonsIds.push(parsedSkeleton.id);
  52593. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  52594. }
  52595. }
  52596. }
  52597. }
  52598. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52599. meshes.push(mesh);
  52600. log += "\n\tMesh " + mesh.toString(fullDetails);
  52601. }
  52602. }
  52603. // Connecting parents
  52604. var currentMesh;
  52605. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52606. currentMesh = scene.meshes[index];
  52607. if (currentMesh._waitingParentId) {
  52608. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  52609. currentMesh._waitingParentId = null;
  52610. }
  52611. }
  52612. // freeze and compute world matrix application
  52613. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52614. currentMesh = scene.meshes[index];
  52615. if (currentMesh._waitingFreezeWorldMatrix) {
  52616. currentMesh.freezeWorldMatrix();
  52617. currentMesh._waitingFreezeWorldMatrix = null;
  52618. }
  52619. else {
  52620. currentMesh.computeWorldMatrix(true);
  52621. }
  52622. }
  52623. }
  52624. // Particles
  52625. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52626. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52627. var parsedParticleSystem = parsedData.particleSystems[index];
  52628. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  52629. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  52630. }
  52631. }
  52632. }
  52633. return true;
  52634. }
  52635. catch (err) {
  52636. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  52637. if (onError) {
  52638. onError(msg, err);
  52639. }
  52640. else {
  52641. BABYLON.Tools.Log(msg);
  52642. throw err;
  52643. }
  52644. }
  52645. finally {
  52646. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  52647. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  52648. }
  52649. }
  52650. return false;
  52651. },
  52652. load: function (scene, data, rootUrl, onError) {
  52653. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  52654. // when SceneLoader.debugLogging = true (default), or exception encountered.
  52655. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  52656. // and avoid problems with multiple concurrent .babylon loads.
  52657. var log = "importScene has failed JSON parse";
  52658. try {
  52659. var parsedData = JSON.parse(data);
  52660. log = "";
  52661. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  52662. // Scene
  52663. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  52664. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  52665. }
  52666. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  52667. scene.autoClear = parsedData.autoClear;
  52668. }
  52669. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  52670. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  52671. }
  52672. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  52673. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  52674. }
  52675. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  52676. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  52677. }
  52678. // Fog
  52679. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  52680. scene.fogMode = parsedData.fogMode;
  52681. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  52682. scene.fogStart = parsedData.fogStart;
  52683. scene.fogEnd = parsedData.fogEnd;
  52684. scene.fogDensity = parsedData.fogDensity;
  52685. log += "\tFog mode for scene: ";
  52686. switch (scene.fogMode) {
  52687. // getters not compiling, so using hardcoded
  52688. case 1:
  52689. log += "exp\n";
  52690. break;
  52691. case 2:
  52692. log += "exp2\n";
  52693. break;
  52694. case 3:
  52695. log += "linear\n";
  52696. break;
  52697. }
  52698. }
  52699. //Physics
  52700. if (parsedData.physicsEnabled) {
  52701. var physicsPlugin;
  52702. if (parsedData.physicsEngine === "cannon") {
  52703. physicsPlugin = new BABYLON.CannonJSPlugin();
  52704. }
  52705. else if (parsedData.physicsEngine === "oimo") {
  52706. physicsPlugin = new BABYLON.OimoJSPlugin();
  52707. }
  52708. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  52709. //else - default engine, which is currently oimo
  52710. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  52711. scene.enablePhysics(physicsGravity, physicsPlugin);
  52712. }
  52713. // Metadata
  52714. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  52715. scene.metadata = parsedData.metadata;
  52716. }
  52717. //collisions, if defined. otherwise, default is true
  52718. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  52719. scene.collisionsEnabled = parsedData.collisionsEnabled;
  52720. }
  52721. scene.workerCollisions = !!parsedData.workerCollisions;
  52722. var index;
  52723. var cache;
  52724. // Lights
  52725. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  52726. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  52727. var parsedLight = parsedData.lights[index];
  52728. var light = BABYLON.Light.Parse(parsedLight, scene);
  52729. if (light) {
  52730. log += (index === 0 ? "\n\tLights:" : "");
  52731. log += "\n\t\t" + light.toString(fullDetails);
  52732. }
  52733. }
  52734. }
  52735. // Animations
  52736. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  52737. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  52738. var parsedAnimation = parsedData.animations[index];
  52739. var animation = BABYLON.Animation.Parse(parsedAnimation);
  52740. scene.animations.push(animation);
  52741. log += (index === 0 ? "\n\tAnimations:" : "");
  52742. log += "\n\t\t" + animation.toString(fullDetails);
  52743. }
  52744. }
  52745. if (parsedData.autoAnimate) {
  52746. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  52747. }
  52748. // Materials
  52749. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  52750. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  52751. var parsedMaterial = parsedData.materials[index];
  52752. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  52753. log += (index === 0 ? "\n\tMaterials:" : "");
  52754. log += "\n\t\t" + mat.toString(fullDetails);
  52755. }
  52756. }
  52757. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  52758. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  52759. var parsedMultiMaterial = parsedData.multiMaterials[index];
  52760. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  52761. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  52762. log += "\n\t\t" + mmat.toString(fullDetails);
  52763. }
  52764. }
  52765. // Morph targets
  52766. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  52767. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  52768. var managerData = _a[_i];
  52769. BABYLON.MorphTargetManager.Parse(managerData, scene);
  52770. }
  52771. }
  52772. // Skeletons
  52773. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  52774. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  52775. var parsedSkeleton = parsedData.skeletons[index];
  52776. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  52777. log += (index === 0 ? "\n\tSkeletons:" : "");
  52778. log += "\n\t\t" + skeleton.toString(fullDetails);
  52779. }
  52780. }
  52781. // Geometries
  52782. var geometries = parsedData.geometries;
  52783. if (geometries !== undefined && geometries !== null) {
  52784. // Boxes
  52785. var boxes = geometries.boxes;
  52786. if (boxes !== undefined && boxes !== null) {
  52787. for (index = 0, cache = boxes.length; index < cache; index++) {
  52788. var parsedBox = boxes[index];
  52789. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  52790. }
  52791. }
  52792. // Spheres
  52793. var spheres = geometries.spheres;
  52794. if (spheres !== undefined && spheres !== null) {
  52795. for (index = 0, cache = spheres.length; index < cache; index++) {
  52796. var parsedSphere = spheres[index];
  52797. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  52798. }
  52799. }
  52800. // Cylinders
  52801. var cylinders = geometries.cylinders;
  52802. if (cylinders !== undefined && cylinders !== null) {
  52803. for (index = 0, cache = cylinders.length; index < cache; index++) {
  52804. var parsedCylinder = cylinders[index];
  52805. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  52806. }
  52807. }
  52808. // Toruses
  52809. var toruses = geometries.toruses;
  52810. if (toruses !== undefined && toruses !== null) {
  52811. for (index = 0, cache = toruses.length; index < cache; index++) {
  52812. var parsedTorus = toruses[index];
  52813. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  52814. }
  52815. }
  52816. // Grounds
  52817. var grounds = geometries.grounds;
  52818. if (grounds !== undefined && grounds !== null) {
  52819. for (index = 0, cache = grounds.length; index < cache; index++) {
  52820. var parsedGround = grounds[index];
  52821. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  52822. }
  52823. }
  52824. // Planes
  52825. var planes = geometries.planes;
  52826. if (planes !== undefined && planes !== null) {
  52827. for (index = 0, cache = planes.length; index < cache; index++) {
  52828. var parsedPlane = planes[index];
  52829. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  52830. }
  52831. }
  52832. // TorusKnots
  52833. var torusKnots = geometries.torusKnots;
  52834. if (torusKnots !== undefined && torusKnots !== null) {
  52835. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  52836. var parsedTorusKnot = torusKnots[index];
  52837. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  52838. }
  52839. }
  52840. // VertexData
  52841. var vertexData = geometries.vertexData;
  52842. if (vertexData !== undefined && vertexData !== null) {
  52843. for (index = 0, cache = vertexData.length; index < cache; index++) {
  52844. var parsedVertexData = vertexData[index];
  52845. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  52846. }
  52847. }
  52848. }
  52849. // Meshes
  52850. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  52851. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  52852. var parsedMesh = parsedData.meshes[index];
  52853. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  52854. log += (index === 0 ? "\n\tMeshes:" : "");
  52855. log += "\n\t\t" + mesh.toString(fullDetails);
  52856. }
  52857. }
  52858. // Cameras
  52859. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  52860. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  52861. var parsedCamera = parsedData.cameras[index];
  52862. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  52863. log += (index === 0 ? "\n\tCameras:" : "");
  52864. log += "\n\t\t" + camera.toString(fullDetails);
  52865. }
  52866. }
  52867. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  52868. scene.setActiveCameraByID(parsedData.activeCameraID);
  52869. }
  52870. // Browsing all the graph to connect the dots
  52871. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  52872. var camera = scene.cameras[index];
  52873. if (camera._waitingParentId) {
  52874. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  52875. camera._waitingParentId = null;
  52876. }
  52877. }
  52878. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52879. var light_1 = scene.lights[index];
  52880. if (light_1 && light_1._waitingParentId) {
  52881. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  52882. light_1._waitingParentId = null;
  52883. }
  52884. }
  52885. // Sounds
  52886. var loadedSounds = [];
  52887. var loadedSound;
  52888. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  52889. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  52890. var parsedSound = parsedData.sounds[index];
  52891. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  52892. if (!parsedSound.url)
  52893. parsedSound.url = parsedSound.name;
  52894. if (!loadedSounds[parsedSound.url]) {
  52895. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  52896. loadedSounds[parsedSound.url] = loadedSound;
  52897. }
  52898. else {
  52899. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  52900. }
  52901. }
  52902. else {
  52903. new BABYLON.Sound(parsedSound.name, null, scene);
  52904. }
  52905. }
  52906. }
  52907. loadedSounds = [];
  52908. // Connect parents & children and parse actions
  52909. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52910. var mesh = scene.meshes[index];
  52911. if (mesh._waitingParentId) {
  52912. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  52913. mesh._waitingParentId = null;
  52914. }
  52915. if (mesh._waitingActions) {
  52916. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  52917. mesh._waitingActions = null;
  52918. }
  52919. }
  52920. // freeze world matrix application
  52921. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  52922. var currentMesh = scene.meshes[index];
  52923. if (currentMesh._waitingFreezeWorldMatrix) {
  52924. currentMesh.freezeWorldMatrix();
  52925. currentMesh._waitingFreezeWorldMatrix = null;
  52926. }
  52927. else {
  52928. currentMesh.computeWorldMatrix(true);
  52929. }
  52930. }
  52931. // Particles Systems
  52932. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  52933. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  52934. var parsedParticleSystem = parsedData.particleSystems[index];
  52935. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  52936. }
  52937. }
  52938. // Environment texture
  52939. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  52940. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  52941. if (parsedData.createDefaultSkybox === true) {
  52942. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  52943. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  52944. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  52945. }
  52946. }
  52947. // Lens flares
  52948. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  52949. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  52950. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  52951. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  52952. }
  52953. }
  52954. // Shadows
  52955. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  52956. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  52957. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  52958. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  52959. }
  52960. }
  52961. // Lights exclusions / inclusions
  52962. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  52963. var light_2 = scene.lights[index];
  52964. // Excluded check
  52965. if (light_2._excludedMeshesIds.length > 0) {
  52966. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  52967. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  52968. if (excludedMesh) {
  52969. light_2.excludedMeshes.push(excludedMesh);
  52970. }
  52971. }
  52972. light_2._excludedMeshesIds = [];
  52973. }
  52974. // Included check
  52975. if (light_2._includedOnlyMeshesIds.length > 0) {
  52976. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  52977. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  52978. if (includedOnlyMesh) {
  52979. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  52980. }
  52981. }
  52982. light_2._includedOnlyMeshesIds = [];
  52983. }
  52984. }
  52985. // Actions (scene)
  52986. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  52987. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  52988. }
  52989. // Finish
  52990. return true;
  52991. }
  52992. catch (err) {
  52993. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  52994. if (onError) {
  52995. onError(msg, err);
  52996. }
  52997. else {
  52998. BABYLON.Tools.Log(msg);
  52999. throw err;
  53000. }
  53001. }
  53002. finally {
  53003. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  53004. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  53005. }
  53006. }
  53007. return false;
  53008. }
  53009. });
  53010. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53011. })(BABYLON || (BABYLON = {}));
  53012. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  53013. var BABYLON;
  53014. (function (BABYLON) {
  53015. var FilesInput = /** @class */ (function () {
  53016. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  53017. this.onProcessFileCallback = function () { return true; };
  53018. this._engine = engine;
  53019. this._currentScene = scene;
  53020. this._sceneLoadedCallback = sceneLoadedCallback;
  53021. this._progressCallback = progressCallback;
  53022. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  53023. this._textureLoadingCallback = textureLoadingCallback;
  53024. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  53025. this._onReloadCallback = onReloadCallback;
  53026. this._errorCallback = errorCallback;
  53027. }
  53028. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  53029. var _this = this;
  53030. if (elementToMonitor) {
  53031. this._elementToMonitor = elementToMonitor;
  53032. this._dragEnterHandler = function (e) { _this.drag(e); };
  53033. this._dragOverHandler = function (e) { _this.drag(e); };
  53034. this._dropHandler = function (e) { _this.drop(e); };
  53035. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  53036. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  53037. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  53038. }
  53039. };
  53040. FilesInput.prototype.dispose = function () {
  53041. if (!this._elementToMonitor) {
  53042. return;
  53043. }
  53044. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  53045. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  53046. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  53047. };
  53048. FilesInput.prototype.renderFunction = function () {
  53049. if (this._additionalRenderLoopLogicCallback) {
  53050. this._additionalRenderLoopLogicCallback();
  53051. }
  53052. if (this._currentScene) {
  53053. if (this._textureLoadingCallback) {
  53054. var remaining = this._currentScene.getWaitingItemsCount();
  53055. if (remaining > 0) {
  53056. this._textureLoadingCallback(remaining);
  53057. }
  53058. }
  53059. this._currentScene.render();
  53060. }
  53061. };
  53062. FilesInput.prototype.drag = function (e) {
  53063. e.stopPropagation();
  53064. e.preventDefault();
  53065. };
  53066. FilesInput.prototype.drop = function (eventDrop) {
  53067. eventDrop.stopPropagation();
  53068. eventDrop.preventDefault();
  53069. this.loadFiles(eventDrop);
  53070. };
  53071. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  53072. var _this = this;
  53073. var reader = folder.createReader();
  53074. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  53075. reader.readEntries(function (entries) {
  53076. remaining.count += entries.length;
  53077. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  53078. var entry = entries_1[_i];
  53079. if (entry.isFile) {
  53080. entry.file(function (file) {
  53081. file.correctName = relativePath + file.name;
  53082. files.push(file);
  53083. if (--remaining.count === 0) {
  53084. callback();
  53085. }
  53086. });
  53087. }
  53088. else if (entry.isDirectory) {
  53089. _this._traverseFolder(entry, files, remaining, callback);
  53090. }
  53091. }
  53092. if (--remaining.count) {
  53093. callback();
  53094. }
  53095. });
  53096. };
  53097. FilesInput.prototype._processFiles = function (files) {
  53098. var skippedFiles = 0;
  53099. for (var i = 0; i < files.length; i++) {
  53100. var name = files[i].correctName.toLowerCase();
  53101. var extension = name.split('.').pop();
  53102. if (!this.onProcessFileCallback(files[i], name, extension)) {
  53103. skippedFiles++;
  53104. continue;
  53105. }
  53106. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  53107. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  53108. this._sceneFileToLoad = files[i];
  53109. }
  53110. else {
  53111. FilesInput.FilesToLoad[name] = files[i];
  53112. }
  53113. }
  53114. if (this._onReloadCallback) {
  53115. this._onReloadCallback(this._sceneFileToLoad);
  53116. }
  53117. else if (skippedFiles < files.length) {
  53118. this.reload();
  53119. }
  53120. };
  53121. FilesInput.prototype.loadFiles = function (event) {
  53122. var _this = this;
  53123. if (this._startingProcessingFilesCallback)
  53124. this._startingProcessingFilesCallback();
  53125. // Handling data transfer via drag'n'drop
  53126. if (event && event.dataTransfer && event.dataTransfer.files) {
  53127. this._filesToLoad = event.dataTransfer.files;
  53128. }
  53129. // Handling files from input files
  53130. if (event && event.target && event.target.files) {
  53131. this._filesToLoad = event.target.files;
  53132. }
  53133. if (this._filesToLoad && this._filesToLoad.length > 0) {
  53134. var files_1 = new Array();
  53135. var folders = [];
  53136. var items = event.dataTransfer ? event.dataTransfer.items : null;
  53137. for (var i = 0; i < this._filesToLoad.length; i++) {
  53138. var fileToLoad = this._filesToLoad[i];
  53139. var name_1 = fileToLoad.name.toLowerCase();
  53140. var entry = void 0;
  53141. fileToLoad.correctName = name_1;
  53142. if (items) {
  53143. var item = items[i];
  53144. if (item.getAsEntry) {
  53145. entry = item.getAsEntry();
  53146. }
  53147. else if (item.webkitGetAsEntry) {
  53148. entry = item.webkitGetAsEntry();
  53149. }
  53150. }
  53151. if (!entry) {
  53152. files_1.push(fileToLoad);
  53153. }
  53154. else {
  53155. if (entry.isDirectory) {
  53156. folders.push(entry);
  53157. }
  53158. else {
  53159. files_1.push(fileToLoad);
  53160. }
  53161. }
  53162. }
  53163. if (folders.length === 0) {
  53164. this._processFiles(files_1);
  53165. }
  53166. else {
  53167. var remaining = { count: folders.length };
  53168. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  53169. var folder = folders_1[_i];
  53170. this._traverseFolder(folder, files_1, remaining, function () {
  53171. _this._processFiles(files_1);
  53172. });
  53173. }
  53174. }
  53175. }
  53176. };
  53177. FilesInput.prototype.reload = function () {
  53178. var _this = this;
  53179. // If a ".babylon" file has been provided
  53180. if (this._sceneFileToLoad) {
  53181. if (this._currentScene) {
  53182. if (BABYLON.Tools.errorsCount > 0) {
  53183. BABYLON.Tools.ClearLogCache();
  53184. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  53185. }
  53186. this._engine.stopRenderLoop();
  53187. this._currentScene.dispose();
  53188. }
  53189. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  53190. _this._currentScene = newScene;
  53191. if (_this._sceneLoadedCallback) {
  53192. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  53193. }
  53194. // Wait for textures and shaders to be ready
  53195. _this._currentScene.executeWhenReady(function () {
  53196. _this._engine.runRenderLoop(function () {
  53197. _this.renderFunction();
  53198. });
  53199. });
  53200. }, function (progress) {
  53201. if (_this._progressCallback) {
  53202. _this._progressCallback(progress);
  53203. }
  53204. }, function (scene, message) {
  53205. _this._currentScene = scene;
  53206. if (_this._errorCallback) {
  53207. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  53208. }
  53209. });
  53210. }
  53211. else {
  53212. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  53213. }
  53214. };
  53215. FilesInput.FilesToLoad = {};
  53216. return FilesInput;
  53217. }());
  53218. BABYLON.FilesInput = FilesInput;
  53219. })(BABYLON || (BABYLON = {}));
  53220. //# sourceMappingURL=babylon.filesInput.js.map
  53221. var BABYLON;
  53222. (function (BABYLON) {
  53223. /**
  53224. * This class implement a typical dictionary using a string as key and the generic type T as value.
  53225. * The underlying implementation relies on an associative array to ensure the best performances.
  53226. * The value can be anything including 'null' but except 'undefined'
  53227. */
  53228. var StringDictionary = /** @class */ (function () {
  53229. function StringDictionary() {
  53230. this._count = 0;
  53231. this._data = {};
  53232. }
  53233. /**
  53234. * This will clear this dictionary and copy the content from the 'source' one.
  53235. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  53236. * @param source the dictionary to take the content from and copy to this dictionary
  53237. */
  53238. StringDictionary.prototype.copyFrom = function (source) {
  53239. var _this = this;
  53240. this.clear();
  53241. source.forEach(function (t, v) { return _this.add(t, v); });
  53242. };
  53243. /**
  53244. * Get a value based from its key
  53245. * @param key the given key to get the matching value from
  53246. * @return the value if found, otherwise undefined is returned
  53247. */
  53248. StringDictionary.prototype.get = function (key) {
  53249. var val = this._data[key];
  53250. if (val !== undefined) {
  53251. return val;
  53252. }
  53253. return undefined;
  53254. };
  53255. /**
  53256. * Get a value from its key or add it if it doesn't exist.
  53257. * This method will ensure you that a given key/data will be present in the dictionary.
  53258. * @param key the given key to get the matching value from
  53259. * @param factory the factory that will create the value if the key is not present in the dictionary.
  53260. * The factory will only be invoked if there's no data for the given key.
  53261. * @return the value corresponding to the key.
  53262. */
  53263. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  53264. var val = this.get(key);
  53265. if (val !== undefined) {
  53266. return val;
  53267. }
  53268. val = factory(key);
  53269. if (val) {
  53270. this.add(key, val);
  53271. }
  53272. return val;
  53273. };
  53274. /**
  53275. * Get a value from its key if present in the dictionary otherwise add it
  53276. * @param key the key to get the value from
  53277. * @param val if there's no such key/value pair in the dictionary add it with this value
  53278. * @return the value corresponding to the key
  53279. */
  53280. StringDictionary.prototype.getOrAdd = function (key, val) {
  53281. var curVal = this.get(key);
  53282. if (curVal !== undefined) {
  53283. return curVal;
  53284. }
  53285. this.add(key, val);
  53286. return val;
  53287. };
  53288. /**
  53289. * Check if there's a given key in the dictionary
  53290. * @param key the key to check for
  53291. * @return true if the key is present, false otherwise
  53292. */
  53293. StringDictionary.prototype.contains = function (key) {
  53294. return this._data[key] !== undefined;
  53295. };
  53296. /**
  53297. * Add a new key and its corresponding value
  53298. * @param key the key to add
  53299. * @param value the value corresponding to the key
  53300. * @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
  53301. */
  53302. StringDictionary.prototype.add = function (key, value) {
  53303. if (this._data[key] !== undefined) {
  53304. return false;
  53305. }
  53306. this._data[key] = value;
  53307. ++this._count;
  53308. return true;
  53309. };
  53310. StringDictionary.prototype.set = function (key, value) {
  53311. if (this._data[key] === undefined) {
  53312. return false;
  53313. }
  53314. this._data[key] = value;
  53315. return true;
  53316. };
  53317. /**
  53318. * Get the element of the given key and remove it from the dictionary
  53319. * @param key
  53320. */
  53321. StringDictionary.prototype.getAndRemove = function (key) {
  53322. var val = this.get(key);
  53323. if (val !== undefined) {
  53324. delete this._data[key];
  53325. --this._count;
  53326. return val;
  53327. }
  53328. return null;
  53329. };
  53330. /**
  53331. * Remove a key/value from the dictionary.
  53332. * @param key the key to remove
  53333. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  53334. */
  53335. StringDictionary.prototype.remove = function (key) {
  53336. if (this.contains(key)) {
  53337. delete this._data[key];
  53338. --this._count;
  53339. return true;
  53340. }
  53341. return false;
  53342. };
  53343. /**
  53344. * Clear the whole content of the dictionary
  53345. */
  53346. StringDictionary.prototype.clear = function () {
  53347. this._data = {};
  53348. this._count = 0;
  53349. };
  53350. Object.defineProperty(StringDictionary.prototype, "count", {
  53351. get: function () {
  53352. return this._count;
  53353. },
  53354. enumerable: true,
  53355. configurable: true
  53356. });
  53357. /**
  53358. * Execute a callback on each key/val of the dictionary.
  53359. * Note that you can remove any element in this dictionary in the callback implementation
  53360. * @param callback the callback to execute on a given key/value pair
  53361. */
  53362. StringDictionary.prototype.forEach = function (callback) {
  53363. for (var cur in this._data) {
  53364. var val = this._data[cur];
  53365. callback(cur, val);
  53366. }
  53367. };
  53368. /**
  53369. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  53370. * If the callback returns null or undefined the method will iterate to the next key/value pair
  53371. * Note that you can remove any element in this dictionary in the callback implementation
  53372. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  53373. */
  53374. StringDictionary.prototype.first = function (callback) {
  53375. for (var cur in this._data) {
  53376. var val = this._data[cur];
  53377. var res = callback(cur, val);
  53378. if (res) {
  53379. return res;
  53380. }
  53381. }
  53382. return null;
  53383. };
  53384. return StringDictionary;
  53385. }());
  53386. BABYLON.StringDictionary = StringDictionary;
  53387. })(BABYLON || (BABYLON = {}));
  53388. //# sourceMappingURL=babylon.stringDictionary.js.map
  53389. var BABYLON;
  53390. (function (BABYLON) {
  53391. var Tags = /** @class */ (function () {
  53392. function Tags() {
  53393. }
  53394. Tags.EnableFor = function (obj) {
  53395. obj._tags = obj._tags || {};
  53396. obj.hasTags = function () {
  53397. return Tags.HasTags(obj);
  53398. };
  53399. obj.addTags = function (tagsString) {
  53400. return Tags.AddTagsTo(obj, tagsString);
  53401. };
  53402. obj.removeTags = function (tagsString) {
  53403. return Tags.RemoveTagsFrom(obj, tagsString);
  53404. };
  53405. obj.matchesTagsQuery = function (tagsQuery) {
  53406. return Tags.MatchesQuery(obj, tagsQuery);
  53407. };
  53408. };
  53409. Tags.DisableFor = function (obj) {
  53410. delete obj._tags;
  53411. delete obj.hasTags;
  53412. delete obj.addTags;
  53413. delete obj.removeTags;
  53414. delete obj.matchesTagsQuery;
  53415. };
  53416. Tags.HasTags = function (obj) {
  53417. if (!obj._tags) {
  53418. return false;
  53419. }
  53420. return !BABYLON.Tools.IsEmpty(obj._tags);
  53421. };
  53422. Tags.GetTags = function (obj, asString) {
  53423. if (asString === void 0) { asString = true; }
  53424. if (!obj._tags) {
  53425. return null;
  53426. }
  53427. if (asString) {
  53428. var tagsArray = [];
  53429. for (var tag in obj._tags) {
  53430. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  53431. tagsArray.push(tag);
  53432. }
  53433. }
  53434. return tagsArray.join(" ");
  53435. }
  53436. else {
  53437. return obj._tags;
  53438. }
  53439. };
  53440. // the tags 'true' and 'false' are reserved and cannot be used as tags
  53441. // a tag cannot start with '||', '&&', and '!'
  53442. // it cannot contain whitespaces
  53443. Tags.AddTagsTo = function (obj, tagsString) {
  53444. if (!tagsString) {
  53445. return;
  53446. }
  53447. if (typeof tagsString !== "string") {
  53448. return;
  53449. }
  53450. var tags = tagsString.split(" ");
  53451. tags.forEach(function (tag, index, array) {
  53452. Tags._AddTagTo(obj, tag);
  53453. });
  53454. };
  53455. Tags._AddTagTo = function (obj, tag) {
  53456. tag = tag.trim();
  53457. if (tag === "" || tag === "true" || tag === "false") {
  53458. return;
  53459. }
  53460. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  53461. return;
  53462. }
  53463. Tags.EnableFor(obj);
  53464. obj._tags[tag] = true;
  53465. };
  53466. Tags.RemoveTagsFrom = function (obj, tagsString) {
  53467. if (!Tags.HasTags(obj)) {
  53468. return;
  53469. }
  53470. var tags = tagsString.split(" ");
  53471. for (var t in tags) {
  53472. Tags._RemoveTagFrom(obj, tags[t]);
  53473. }
  53474. };
  53475. Tags._RemoveTagFrom = function (obj, tag) {
  53476. delete obj._tags[tag];
  53477. };
  53478. Tags.MatchesQuery = function (obj, tagsQuery) {
  53479. if (tagsQuery === undefined) {
  53480. return true;
  53481. }
  53482. if (tagsQuery === "") {
  53483. return Tags.HasTags(obj);
  53484. }
  53485. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  53486. };
  53487. return Tags;
  53488. }());
  53489. BABYLON.Tags = Tags;
  53490. })(BABYLON || (BABYLON = {}));
  53491. //# sourceMappingURL=babylon.tags.js.map
  53492. var BABYLON;
  53493. (function (BABYLON) {
  53494. var Internals;
  53495. (function (Internals) {
  53496. var AndOrNotEvaluator = /** @class */ (function () {
  53497. function AndOrNotEvaluator() {
  53498. }
  53499. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  53500. if (!query.match(/\([^\(\)]*\)/g)) {
  53501. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  53502. }
  53503. else {
  53504. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  53505. // remove parenthesis
  53506. r = r.slice(1, r.length - 1);
  53507. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  53508. });
  53509. }
  53510. if (query === "true") {
  53511. return true;
  53512. }
  53513. if (query === "false") {
  53514. return false;
  53515. }
  53516. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  53517. };
  53518. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  53519. evaluateCallback = evaluateCallback || (function (r) {
  53520. return r === "true" ? true : false;
  53521. });
  53522. var result;
  53523. var or = parenthesisContent.split("||");
  53524. for (var i in or) {
  53525. if (or.hasOwnProperty(i)) {
  53526. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  53527. var and = ori.split("&&");
  53528. if (and.length > 1) {
  53529. for (var j = 0; j < and.length; ++j) {
  53530. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  53531. if (andj !== "true" && andj !== "false") {
  53532. if (andj[0] === "!") {
  53533. result = !evaluateCallback(andj.substring(1));
  53534. }
  53535. else {
  53536. result = evaluateCallback(andj);
  53537. }
  53538. }
  53539. else {
  53540. result = andj === "true" ? true : false;
  53541. }
  53542. if (!result) {
  53543. ori = "false";
  53544. break;
  53545. }
  53546. }
  53547. }
  53548. if (result || ori === "true") {
  53549. result = true;
  53550. break;
  53551. }
  53552. // result equals false (or undefined)
  53553. if (ori !== "true" && ori !== "false") {
  53554. if (ori[0] === "!") {
  53555. result = !evaluateCallback(ori.substring(1));
  53556. }
  53557. else {
  53558. result = evaluateCallback(ori);
  53559. }
  53560. }
  53561. else {
  53562. result = ori === "true" ? true : false;
  53563. }
  53564. }
  53565. }
  53566. // the whole parenthesis scope is replaced by 'true' or 'false'
  53567. return result ? "true" : "false";
  53568. };
  53569. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  53570. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  53571. // remove whitespaces
  53572. r = r.replace(/[\s]/g, function () { return ""; });
  53573. return r.length % 2 ? "!" : "";
  53574. });
  53575. booleanString = booleanString.trim();
  53576. if (booleanString === "!true") {
  53577. booleanString = "false";
  53578. }
  53579. else if (booleanString === "!false") {
  53580. booleanString = "true";
  53581. }
  53582. return booleanString;
  53583. };
  53584. return AndOrNotEvaluator;
  53585. }());
  53586. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  53587. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53588. })(BABYLON || (BABYLON = {}));
  53589. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  53590. var BABYLON;
  53591. (function (BABYLON) {
  53592. var Database = /** @class */ (function () {
  53593. function Database(urlToScene, callbackManifestChecked) {
  53594. // Handling various flavors of prefixed version of IndexedDB
  53595. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  53596. this.callbackManifestChecked = callbackManifestChecked;
  53597. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  53598. this.db = null;
  53599. this._enableSceneOffline = false;
  53600. this._enableTexturesOffline = false;
  53601. this.manifestVersionFound = 0;
  53602. this.mustUpdateRessources = false;
  53603. this.hasReachedQuota = false;
  53604. if (!Database.IDBStorageEnabled) {
  53605. this.callbackManifestChecked(true);
  53606. }
  53607. else {
  53608. this.checkManifestFile();
  53609. }
  53610. }
  53611. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  53612. get: function () {
  53613. return this._enableSceneOffline;
  53614. },
  53615. enumerable: true,
  53616. configurable: true
  53617. });
  53618. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  53619. get: function () {
  53620. return this._enableTexturesOffline;
  53621. },
  53622. enumerable: true,
  53623. configurable: true
  53624. });
  53625. Database.prototype.checkManifestFile = function () {
  53626. var _this = this;
  53627. var noManifestFile = function () {
  53628. _this._enableSceneOffline = false;
  53629. _this._enableTexturesOffline = false;
  53630. _this.callbackManifestChecked(false);
  53631. };
  53632. var timeStampUsed = false;
  53633. var manifestURL = this.currentSceneUrl + ".manifest";
  53634. var xhr = new XMLHttpRequest();
  53635. if (navigator.onLine) {
  53636. // Adding a timestamp to by-pass browsers' cache
  53637. timeStampUsed = true;
  53638. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  53639. }
  53640. xhr.open("GET", manifestURL, true);
  53641. xhr.addEventListener("load", function () {
  53642. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  53643. try {
  53644. var manifestFile = JSON.parse(xhr.response);
  53645. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  53646. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  53647. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  53648. _this.manifestVersionFound = manifestFile.version;
  53649. }
  53650. if (_this.callbackManifestChecked) {
  53651. _this.callbackManifestChecked(true);
  53652. }
  53653. }
  53654. catch (ex) {
  53655. noManifestFile();
  53656. }
  53657. }
  53658. else {
  53659. noManifestFile();
  53660. }
  53661. }, false);
  53662. xhr.addEventListener("error", function (event) {
  53663. if (timeStampUsed) {
  53664. timeStampUsed = false;
  53665. // Let's retry without the timeStamp
  53666. // It could fail when coupled with HTML5 Offline API
  53667. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  53668. xhr.open("GET", retryManifestURL, true);
  53669. xhr.send();
  53670. }
  53671. else {
  53672. noManifestFile();
  53673. }
  53674. }, false);
  53675. try {
  53676. xhr.send();
  53677. }
  53678. catch (ex) {
  53679. BABYLON.Tools.Error("Error on XHR send request.");
  53680. this.callbackManifestChecked(false);
  53681. }
  53682. };
  53683. Database.prototype.openAsync = function (successCallback, errorCallback) {
  53684. var _this = this;
  53685. var handleError = function () {
  53686. _this.isSupported = false;
  53687. if (errorCallback)
  53688. errorCallback();
  53689. };
  53690. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  53691. // Your browser doesn't support IndexedDB
  53692. this.isSupported = false;
  53693. if (errorCallback)
  53694. errorCallback();
  53695. }
  53696. else {
  53697. // If the DB hasn't been opened or created yet
  53698. if (!this.db) {
  53699. this.hasReachedQuota = false;
  53700. this.isSupported = true;
  53701. var request = this.idbFactory.open("babylonjs", 1);
  53702. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  53703. request.onerror = function (event) {
  53704. handleError();
  53705. };
  53706. // executes when a version change transaction cannot complete due to other active transactions
  53707. request.onblocked = function (event) {
  53708. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  53709. handleError();
  53710. };
  53711. // DB has been opened successfully
  53712. request.onsuccess = function (event) {
  53713. _this.db = request.result;
  53714. successCallback();
  53715. };
  53716. // Initialization of the DB. Creating Scenes & Textures stores
  53717. request.onupgradeneeded = function (event) {
  53718. _this.db = (event.target).result;
  53719. if (_this.db) {
  53720. try {
  53721. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  53722. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  53723. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  53724. }
  53725. catch (ex) {
  53726. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  53727. handleError();
  53728. }
  53729. }
  53730. };
  53731. }
  53732. else {
  53733. if (successCallback)
  53734. successCallback();
  53735. }
  53736. }
  53737. };
  53738. Database.prototype.loadImageFromDB = function (url, image) {
  53739. var _this = this;
  53740. var completeURL = Database.ReturnFullUrlLocation(url);
  53741. var saveAndLoadImage = function () {
  53742. if (!_this.hasReachedQuota && _this.db !== null) {
  53743. // the texture is not yet in the DB, let's try to save it
  53744. _this._saveImageIntoDBAsync(completeURL, image);
  53745. }
  53746. else {
  53747. image.src = url;
  53748. }
  53749. };
  53750. if (!this.mustUpdateRessources) {
  53751. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  53752. }
  53753. else {
  53754. saveAndLoadImage();
  53755. }
  53756. };
  53757. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  53758. if (this.isSupported && this.db !== null) {
  53759. var texture;
  53760. var transaction = this.db.transaction(["textures"]);
  53761. transaction.onabort = function (event) {
  53762. image.src = url;
  53763. };
  53764. transaction.oncomplete = function (event) {
  53765. var blobTextureURL;
  53766. if (texture) {
  53767. var URL = window.URL || window.webkitURL;
  53768. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  53769. image.onerror = function () {
  53770. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  53771. image.src = url;
  53772. };
  53773. image.src = blobTextureURL;
  53774. }
  53775. else {
  53776. notInDBCallback();
  53777. }
  53778. };
  53779. var getRequest = transaction.objectStore("textures").get(url);
  53780. getRequest.onsuccess = function (event) {
  53781. texture = (event.target).result;
  53782. };
  53783. getRequest.onerror = function (event) {
  53784. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  53785. image.src = url;
  53786. };
  53787. }
  53788. else {
  53789. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53790. image.src = url;
  53791. }
  53792. };
  53793. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  53794. var _this = this;
  53795. if (this.isSupported) {
  53796. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  53797. var generateBlobUrl = function () {
  53798. var blobTextureURL;
  53799. if (blob) {
  53800. var URL = window.URL || window.webkitURL;
  53801. try {
  53802. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  53803. }
  53804. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  53805. catch (ex) {
  53806. blobTextureURL = URL.createObjectURL(blob);
  53807. }
  53808. }
  53809. if (blobTextureURL) {
  53810. image.src = blobTextureURL;
  53811. }
  53812. };
  53813. if (Database.IsUASupportingBlobStorage) {
  53814. var xhr = new XMLHttpRequest(), blob;
  53815. xhr.open("GET", url, true);
  53816. xhr.responseType = "blob";
  53817. xhr.addEventListener("load", function () {
  53818. if (xhr.status === 200 && _this.db) {
  53819. // Blob as response (XHR2)
  53820. blob = xhr.response;
  53821. var transaction = _this.db.transaction(["textures"], "readwrite");
  53822. // the transaction could abort because of a QuotaExceededError error
  53823. transaction.onabort = function (event) {
  53824. try {
  53825. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  53826. var srcElement = (event.srcElement || event.target);
  53827. var error = srcElement.error;
  53828. if (error && error.name === "QuotaExceededError") {
  53829. _this.hasReachedQuota = true;
  53830. }
  53831. }
  53832. catch (ex) { }
  53833. generateBlobUrl();
  53834. };
  53835. transaction.oncomplete = function (event) {
  53836. generateBlobUrl();
  53837. };
  53838. var newTexture = { textureUrl: url, data: blob };
  53839. try {
  53840. // Put the blob into the dabase
  53841. var addRequest = transaction.objectStore("textures").put(newTexture);
  53842. addRequest.onsuccess = function (event) {
  53843. };
  53844. addRequest.onerror = function (event) {
  53845. generateBlobUrl();
  53846. };
  53847. }
  53848. catch (ex) {
  53849. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  53850. if (ex.code === 25) {
  53851. Database.IsUASupportingBlobStorage = false;
  53852. }
  53853. image.src = url;
  53854. }
  53855. }
  53856. else {
  53857. image.src = url;
  53858. }
  53859. }, false);
  53860. xhr.addEventListener("error", function (event) {
  53861. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  53862. image.src = url;
  53863. }, false);
  53864. xhr.send();
  53865. }
  53866. else {
  53867. image.src = url;
  53868. }
  53869. }
  53870. else {
  53871. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53872. image.src = url;
  53873. }
  53874. };
  53875. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  53876. var _this = this;
  53877. var updateVersion = function () {
  53878. // the version is not yet in the DB or we need to update it
  53879. _this._saveVersionIntoDBAsync(url, versionLoaded);
  53880. };
  53881. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  53882. };
  53883. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  53884. var _this = this;
  53885. if (this.isSupported && this.db) {
  53886. var version;
  53887. try {
  53888. var transaction = this.db.transaction(["versions"]);
  53889. transaction.oncomplete = function (event) {
  53890. if (version) {
  53891. // If the version in the JSON file is > than the version in DB
  53892. if (_this.manifestVersionFound > version.data) {
  53893. _this.mustUpdateRessources = true;
  53894. updateInDBCallback();
  53895. }
  53896. else {
  53897. callback(version.data);
  53898. }
  53899. }
  53900. else {
  53901. _this.mustUpdateRessources = true;
  53902. updateInDBCallback();
  53903. }
  53904. };
  53905. transaction.onabort = function (event) {
  53906. callback(-1);
  53907. };
  53908. var getRequest = transaction.objectStore("versions").get(url);
  53909. getRequest.onsuccess = function (event) {
  53910. version = (event.target).result;
  53911. };
  53912. getRequest.onerror = function (event) {
  53913. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  53914. callback(-1);
  53915. };
  53916. }
  53917. catch (ex) {
  53918. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  53919. callback(-1);
  53920. }
  53921. }
  53922. else {
  53923. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  53924. callback(-1);
  53925. }
  53926. };
  53927. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  53928. var _this = this;
  53929. if (this.isSupported && !this.hasReachedQuota && this.db) {
  53930. try {
  53931. // Open a transaction to the database
  53932. var transaction = this.db.transaction(["versions"], "readwrite");
  53933. // the transaction could abort because of a QuotaExceededError error
  53934. transaction.onabort = function (event) {
  53935. try {
  53936. var error = event.srcElement['error'];
  53937. if (error && error.name === "QuotaExceededError") {
  53938. _this.hasReachedQuota = true;
  53939. }
  53940. }
  53941. catch (ex) { }
  53942. callback(-1);
  53943. };
  53944. transaction.oncomplete = function (event) {
  53945. callback(_this.manifestVersionFound);
  53946. };
  53947. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  53948. // Put the scene into the database
  53949. var addRequest = transaction.objectStore("versions").put(newVersion);
  53950. addRequest.onsuccess = function (event) {
  53951. };
  53952. addRequest.onerror = function (event) {
  53953. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  53954. };
  53955. }
  53956. catch (ex) {
  53957. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  53958. callback(-1);
  53959. }
  53960. }
  53961. else {
  53962. callback(-1);
  53963. }
  53964. };
  53965. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  53966. var _this = this;
  53967. var completeUrl = Database.ReturnFullUrlLocation(url);
  53968. var saveAndLoadFile = function () {
  53969. // the scene is not yet in the DB, let's try to save it
  53970. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  53971. };
  53972. this._checkVersionFromDB(completeUrl, function (version) {
  53973. if (version !== -1) {
  53974. if (!_this.mustUpdateRessources) {
  53975. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  53976. }
  53977. else {
  53978. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  53979. }
  53980. }
  53981. else {
  53982. if (errorCallback) {
  53983. errorCallback();
  53984. }
  53985. }
  53986. });
  53987. };
  53988. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  53989. if (this.isSupported && this.db) {
  53990. var targetStore;
  53991. if (url.indexOf(".babylon") !== -1) {
  53992. targetStore = "scenes";
  53993. }
  53994. else {
  53995. targetStore = "textures";
  53996. }
  53997. var file;
  53998. var transaction = this.db.transaction([targetStore]);
  53999. transaction.oncomplete = function (event) {
  54000. if (file) {
  54001. callback(file.data);
  54002. }
  54003. else {
  54004. notInDBCallback();
  54005. }
  54006. };
  54007. transaction.onabort = function (event) {
  54008. notInDBCallback();
  54009. };
  54010. var getRequest = transaction.objectStore(targetStore).get(url);
  54011. getRequest.onsuccess = function (event) {
  54012. file = (event.target).result;
  54013. };
  54014. getRequest.onerror = function (event) {
  54015. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  54016. notInDBCallback();
  54017. };
  54018. }
  54019. else {
  54020. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54021. callback();
  54022. }
  54023. };
  54024. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  54025. var _this = this;
  54026. if (this.isSupported) {
  54027. var targetStore;
  54028. if (url.indexOf(".babylon") !== -1) {
  54029. targetStore = "scenes";
  54030. }
  54031. else {
  54032. targetStore = "textures";
  54033. }
  54034. // Create XHR
  54035. var xhr = new XMLHttpRequest();
  54036. var fileData;
  54037. xhr.open("GET", url, true);
  54038. if (useArrayBuffer) {
  54039. xhr.responseType = "arraybuffer";
  54040. }
  54041. if (progressCallback) {
  54042. xhr.onprogress = progressCallback;
  54043. }
  54044. xhr.addEventListener("load", function () {
  54045. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  54046. // Blob as response (XHR2)
  54047. //fileData = xhr.responseText;
  54048. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  54049. if (!_this.hasReachedQuota && _this.db) {
  54050. // Open a transaction to the database
  54051. var transaction = _this.db.transaction([targetStore], "readwrite");
  54052. // the transaction could abort because of a QuotaExceededError error
  54053. transaction.onabort = function (event) {
  54054. try {
  54055. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  54056. var error = event.srcElement['error'];
  54057. if (error && error.name === "QuotaExceededError") {
  54058. _this.hasReachedQuota = true;
  54059. }
  54060. }
  54061. catch (ex) { }
  54062. callback(fileData);
  54063. };
  54064. transaction.oncomplete = function (event) {
  54065. callback(fileData);
  54066. };
  54067. var newFile;
  54068. if (targetStore === "scenes") {
  54069. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  54070. }
  54071. else {
  54072. newFile = { textureUrl: url, data: fileData };
  54073. }
  54074. try {
  54075. // Put the scene into the database
  54076. var addRequest = transaction.objectStore(targetStore).put(newFile);
  54077. addRequest.onsuccess = function (event) {
  54078. };
  54079. addRequest.onerror = function (event) {
  54080. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  54081. };
  54082. }
  54083. catch (ex) {
  54084. callback(fileData);
  54085. }
  54086. }
  54087. else {
  54088. callback(fileData);
  54089. }
  54090. }
  54091. else {
  54092. callback();
  54093. }
  54094. }, false);
  54095. xhr.addEventListener("error", function (event) {
  54096. BABYLON.Tools.Error("error on XHR request.");
  54097. callback();
  54098. }, false);
  54099. xhr.send();
  54100. }
  54101. else {
  54102. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  54103. callback();
  54104. }
  54105. };
  54106. Database.IsUASupportingBlobStorage = true;
  54107. Database.IDBStorageEnabled = true;
  54108. Database.parseURL = function (url) {
  54109. var a = document.createElement('a');
  54110. a.href = url;
  54111. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  54112. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  54113. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  54114. return absLocation;
  54115. };
  54116. Database.ReturnFullUrlLocation = function (url) {
  54117. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  54118. return (Database.parseURL(window.location.href) + url);
  54119. }
  54120. else {
  54121. return url;
  54122. }
  54123. };
  54124. return Database;
  54125. }());
  54126. BABYLON.Database = Database;
  54127. })(BABYLON || (BABYLON = {}));
  54128. //# sourceMappingURL=babylon.database.js.map
  54129. var BABYLON;
  54130. (function (BABYLON) {
  54131. var FresnelParameters = /** @class */ (function () {
  54132. function FresnelParameters() {
  54133. this._isEnabled = true;
  54134. this.leftColor = BABYLON.Color3.White();
  54135. this.rightColor = BABYLON.Color3.Black();
  54136. this.bias = 0;
  54137. this.power = 1;
  54138. }
  54139. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  54140. get: function () {
  54141. return this._isEnabled;
  54142. },
  54143. set: function (value) {
  54144. if (this._isEnabled === value) {
  54145. return;
  54146. }
  54147. this._isEnabled = value;
  54148. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  54149. },
  54150. enumerable: true,
  54151. configurable: true
  54152. });
  54153. FresnelParameters.prototype.clone = function () {
  54154. var newFresnelParameters = new FresnelParameters();
  54155. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  54156. return newFresnelParameters;
  54157. };
  54158. FresnelParameters.prototype.serialize = function () {
  54159. var serializationObject = {};
  54160. serializationObject.isEnabled = this.isEnabled;
  54161. serializationObject.leftColor = this.leftColor;
  54162. serializationObject.rightColor = this.rightColor;
  54163. serializationObject.bias = this.bias;
  54164. serializationObject.power = this.power;
  54165. return serializationObject;
  54166. };
  54167. FresnelParameters.Parse = function (parsedFresnelParameters) {
  54168. var fresnelParameters = new FresnelParameters();
  54169. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  54170. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  54171. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  54172. fresnelParameters.bias = parsedFresnelParameters.bias;
  54173. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  54174. return fresnelParameters;
  54175. };
  54176. return FresnelParameters;
  54177. }());
  54178. BABYLON.FresnelParameters = FresnelParameters;
  54179. })(BABYLON || (BABYLON = {}));
  54180. //# sourceMappingURL=babylon.fresnelParameters.js.map
  54181. var BABYLON;
  54182. (function (BABYLON) {
  54183. var MultiMaterial = /** @class */ (function (_super) {
  54184. __extends(MultiMaterial, _super);
  54185. function MultiMaterial(name, scene) {
  54186. var _this = _super.call(this, name, scene, true) || this;
  54187. scene.multiMaterials.push(_this);
  54188. _this.subMaterials = new Array();
  54189. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  54190. return _this;
  54191. }
  54192. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  54193. get: function () {
  54194. return this._subMaterials;
  54195. },
  54196. set: function (value) {
  54197. this._subMaterials = value;
  54198. this._hookArray(value);
  54199. },
  54200. enumerable: true,
  54201. configurable: true
  54202. });
  54203. MultiMaterial.prototype._hookArray = function (array) {
  54204. var _this = this;
  54205. var oldPush = array.push;
  54206. array.push = function () {
  54207. var items = [];
  54208. for (var _i = 0; _i < arguments.length; _i++) {
  54209. items[_i] = arguments[_i];
  54210. }
  54211. var result = oldPush.apply(array, items);
  54212. _this._markAllSubMeshesAsTexturesDirty();
  54213. return result;
  54214. };
  54215. var oldSplice = array.splice;
  54216. array.splice = function (index, deleteCount) {
  54217. var deleted = oldSplice.apply(array, [index, deleteCount]);
  54218. _this._markAllSubMeshesAsTexturesDirty();
  54219. return deleted;
  54220. };
  54221. };
  54222. // Properties
  54223. MultiMaterial.prototype.getSubMaterial = function (index) {
  54224. if (index < 0 || index >= this.subMaterials.length) {
  54225. return this.getScene().defaultMaterial;
  54226. }
  54227. return this.subMaterials[index];
  54228. };
  54229. MultiMaterial.prototype.getActiveTextures = function () {
  54230. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  54231. if (subMaterial) {
  54232. return subMaterial.getActiveTextures();
  54233. }
  54234. else {
  54235. return [];
  54236. }
  54237. }));
  54238. var _a;
  54239. };
  54240. // Methods
  54241. MultiMaterial.prototype.getClassName = function () {
  54242. return "MultiMaterial";
  54243. };
  54244. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  54245. for (var index = 0; index < this.subMaterials.length; index++) {
  54246. var subMaterial = this.subMaterials[index];
  54247. if (subMaterial) {
  54248. if (subMaterial.storeEffectOnSubMeshes) {
  54249. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  54250. return false;
  54251. }
  54252. continue;
  54253. }
  54254. if (!subMaterial.isReady(mesh)) {
  54255. return false;
  54256. }
  54257. }
  54258. }
  54259. return true;
  54260. };
  54261. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  54262. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  54263. for (var index = 0; index < this.subMaterials.length; index++) {
  54264. var subMaterial = null;
  54265. var current = this.subMaterials[index];
  54266. if (cloneChildren && current) {
  54267. subMaterial = current.clone(name + "-" + current.name);
  54268. }
  54269. else {
  54270. subMaterial = this.subMaterials[index];
  54271. }
  54272. newMultiMaterial.subMaterials.push(subMaterial);
  54273. }
  54274. return newMultiMaterial;
  54275. };
  54276. MultiMaterial.prototype.serialize = function () {
  54277. var serializationObject = {};
  54278. serializationObject.name = this.name;
  54279. serializationObject.id = this.id;
  54280. serializationObject.tags = BABYLON.Tags.GetTags(this);
  54281. serializationObject.materials = [];
  54282. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  54283. var subMat = this.subMaterials[matIndex];
  54284. if (subMat) {
  54285. serializationObject.materials.push(subMat.id);
  54286. }
  54287. else {
  54288. serializationObject.materials.push(null);
  54289. }
  54290. }
  54291. return serializationObject;
  54292. };
  54293. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54294. var scene = this.getScene();
  54295. if (!scene) {
  54296. return;
  54297. }
  54298. var index = scene.multiMaterials.indexOf(this);
  54299. if (index >= 0) {
  54300. scene.multiMaterials.splice(index, 1);
  54301. }
  54302. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54303. };
  54304. return MultiMaterial;
  54305. }(BABYLON.Material));
  54306. BABYLON.MultiMaterial = MultiMaterial;
  54307. })(BABYLON || (BABYLON = {}));
  54308. //# sourceMappingURL=babylon.multiMaterial.js.map
  54309. var BABYLON;
  54310. (function (BABYLON) {
  54311. var FreeCameraTouchInput = /** @class */ (function () {
  54312. function FreeCameraTouchInput() {
  54313. this._offsetX = null;
  54314. this._offsetY = null;
  54315. this._pointerCount = 0;
  54316. this._pointerPressed = new Array();
  54317. this.touchAngularSensibility = 200000.0;
  54318. this.touchMoveSensibility = 250.0;
  54319. }
  54320. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  54321. var _this = this;
  54322. var previousPosition = null;
  54323. if (this._pointerInput === undefined) {
  54324. this._onLostFocus = function (evt) {
  54325. _this._offsetX = null;
  54326. _this._offsetY = null;
  54327. };
  54328. this._pointerInput = function (p, s) {
  54329. var evt = p.event;
  54330. if (evt.pointerType === "mouse") {
  54331. return;
  54332. }
  54333. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  54334. if (!noPreventDefault) {
  54335. evt.preventDefault();
  54336. }
  54337. _this._pointerPressed.push(evt.pointerId);
  54338. if (_this._pointerPressed.length !== 1) {
  54339. return;
  54340. }
  54341. previousPosition = {
  54342. x: evt.clientX,
  54343. y: evt.clientY
  54344. };
  54345. }
  54346. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  54347. if (!noPreventDefault) {
  54348. evt.preventDefault();
  54349. }
  54350. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54351. if (index === -1) {
  54352. return;
  54353. }
  54354. _this._pointerPressed.splice(index, 1);
  54355. if (index != 0) {
  54356. return;
  54357. }
  54358. previousPosition = null;
  54359. _this._offsetX = null;
  54360. _this._offsetY = null;
  54361. }
  54362. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  54363. if (!noPreventDefault) {
  54364. evt.preventDefault();
  54365. }
  54366. if (!previousPosition) {
  54367. return;
  54368. }
  54369. var index = _this._pointerPressed.indexOf(evt.pointerId);
  54370. if (index != 0) {
  54371. return;
  54372. }
  54373. _this._offsetX = evt.clientX - previousPosition.x;
  54374. _this._offsetY = -(evt.clientY - previousPosition.y);
  54375. }
  54376. };
  54377. }
  54378. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  54379. if (this._onLostFocus) {
  54380. element.addEventListener("blur", this._onLostFocus);
  54381. }
  54382. };
  54383. FreeCameraTouchInput.prototype.detachControl = function (element) {
  54384. if (this._pointerInput && element) {
  54385. if (this._observer) {
  54386. this.camera.getScene().onPointerObservable.remove(this._observer);
  54387. this._observer = null;
  54388. }
  54389. if (this._onLostFocus) {
  54390. element.removeEventListener("blur", this._onLostFocus);
  54391. this._onLostFocus = null;
  54392. }
  54393. this._pointerPressed = [];
  54394. this._offsetX = null;
  54395. this._offsetY = null;
  54396. this._pointerCount = 0;
  54397. }
  54398. };
  54399. FreeCameraTouchInput.prototype.checkInputs = function () {
  54400. if (this._offsetX && this._offsetY) {
  54401. var camera = this.camera;
  54402. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  54403. if (this._pointerPressed.length > 1) {
  54404. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  54405. }
  54406. else {
  54407. var speed = camera._computeLocalCameraSpeed();
  54408. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  54409. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  54410. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  54411. }
  54412. }
  54413. };
  54414. FreeCameraTouchInput.prototype.getClassName = function () {
  54415. return "FreeCameraTouchInput";
  54416. };
  54417. FreeCameraTouchInput.prototype.getSimpleName = function () {
  54418. return "touch";
  54419. };
  54420. __decorate([
  54421. BABYLON.serialize()
  54422. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  54423. __decorate([
  54424. BABYLON.serialize()
  54425. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  54426. return FreeCameraTouchInput;
  54427. }());
  54428. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  54429. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  54430. })(BABYLON || (BABYLON = {}));
  54431. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  54432. var BABYLON;
  54433. (function (BABYLON) {
  54434. // We're mainly based on the logic defined into the FreeCamera code
  54435. var TouchCamera = /** @class */ (function (_super) {
  54436. __extends(TouchCamera, _super);
  54437. //-- end properties for backward compatibility for inputs
  54438. function TouchCamera(name, position, scene) {
  54439. var _this = _super.call(this, name, position, scene) || this;
  54440. _this.inputs.addTouch();
  54441. _this._setupInputs();
  54442. return _this;
  54443. }
  54444. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  54445. //-- Begin properties for backward compatibility for inputs
  54446. get: function () {
  54447. var touch = this.inputs.attached["touch"];
  54448. if (touch)
  54449. return touch.touchAngularSensibility;
  54450. return 0;
  54451. },
  54452. set: function (value) {
  54453. var touch = this.inputs.attached["touch"];
  54454. if (touch)
  54455. touch.touchAngularSensibility = value;
  54456. },
  54457. enumerable: true,
  54458. configurable: true
  54459. });
  54460. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  54461. get: function () {
  54462. var touch = this.inputs.attached["touch"];
  54463. if (touch)
  54464. return touch.touchMoveSensibility;
  54465. return 0;
  54466. },
  54467. set: function (value) {
  54468. var touch = this.inputs.attached["touch"];
  54469. if (touch)
  54470. touch.touchMoveSensibility = value;
  54471. },
  54472. enumerable: true,
  54473. configurable: true
  54474. });
  54475. TouchCamera.prototype.getClassName = function () {
  54476. return "TouchCamera";
  54477. };
  54478. TouchCamera.prototype._setupInputs = function () {
  54479. var mouse = this.inputs.attached["mouse"];
  54480. if (mouse) {
  54481. mouse.touchEnabled = false;
  54482. }
  54483. };
  54484. return TouchCamera;
  54485. }(BABYLON.FreeCamera));
  54486. BABYLON.TouchCamera = TouchCamera;
  54487. })(BABYLON || (BABYLON = {}));
  54488. //# sourceMappingURL=babylon.touchCamera.js.map
  54489. var BABYLON;
  54490. (function (BABYLON) {
  54491. var ProceduralTexture = /** @class */ (function (_super) {
  54492. __extends(ProceduralTexture, _super);
  54493. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  54494. if (fallbackTexture === void 0) { fallbackTexture = null; }
  54495. if (generateMipMaps === void 0) { generateMipMaps = true; }
  54496. if (isCube === void 0) { isCube = false; }
  54497. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  54498. _this.isCube = isCube;
  54499. _this.isEnabled = true;
  54500. _this._currentRefreshId = -1;
  54501. _this._refreshRate = 1;
  54502. _this._vertexBuffers = {};
  54503. _this._uniforms = new Array();
  54504. _this._samplers = new Array();
  54505. _this._textures = {};
  54506. _this._floats = {};
  54507. _this._floatsArrays = {};
  54508. _this._colors3 = {};
  54509. _this._colors4 = {};
  54510. _this._vectors2 = {};
  54511. _this._vectors3 = {};
  54512. _this._matrices = {};
  54513. _this._fallbackTextureUsed = false;
  54514. scene._proceduralTextures.push(_this);
  54515. _this._engine = scene.getEngine();
  54516. _this.name = name;
  54517. _this.isRenderTarget = true;
  54518. _this._size = size;
  54519. _this._generateMipMaps = generateMipMaps;
  54520. _this.setFragment(fragment);
  54521. _this._fallbackTexture = fallbackTexture;
  54522. if (isCube) {
  54523. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  54524. _this.setFloat("face", 0);
  54525. }
  54526. else {
  54527. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  54528. }
  54529. // VBO
  54530. var vertices = [];
  54531. vertices.push(1, 1);
  54532. vertices.push(-1, 1);
  54533. vertices.push(-1, -1);
  54534. vertices.push(1, -1);
  54535. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54536. _this._createIndexBuffer();
  54537. return _this;
  54538. }
  54539. ProceduralTexture.prototype._createIndexBuffer = function () {
  54540. var engine = this._engine;
  54541. // Indices
  54542. var indices = [];
  54543. indices.push(0);
  54544. indices.push(1);
  54545. indices.push(2);
  54546. indices.push(0);
  54547. indices.push(2);
  54548. indices.push(3);
  54549. this._indexBuffer = engine.createIndexBuffer(indices);
  54550. };
  54551. ProceduralTexture.prototype._rebuild = function () {
  54552. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54553. if (vb) {
  54554. vb._rebuild();
  54555. }
  54556. this._createIndexBuffer();
  54557. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  54558. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  54559. }
  54560. };
  54561. ProceduralTexture.prototype.reset = function () {
  54562. if (this._effect === undefined) {
  54563. return;
  54564. }
  54565. var engine = this._engine;
  54566. engine._releaseEffect(this._effect);
  54567. };
  54568. ProceduralTexture.prototype.isReady = function () {
  54569. var _this = this;
  54570. var engine = this._engine;
  54571. var shaders;
  54572. if (!this._fragment) {
  54573. return false;
  54574. }
  54575. if (this._fallbackTextureUsed) {
  54576. return true;
  54577. }
  54578. if (this._fragment.fragmentElement !== undefined) {
  54579. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  54580. }
  54581. else {
  54582. shaders = { vertex: "procedural", fragment: this._fragment };
  54583. }
  54584. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  54585. _this.releaseInternalTexture();
  54586. if (_this._fallbackTexture) {
  54587. _this._texture = _this._fallbackTexture._texture;
  54588. if (_this._texture) {
  54589. _this._texture.incrementReferences();
  54590. }
  54591. }
  54592. _this._fallbackTextureUsed = true;
  54593. });
  54594. return this._effect.isReady();
  54595. };
  54596. ProceduralTexture.prototype.resetRefreshCounter = function () {
  54597. this._currentRefreshId = -1;
  54598. };
  54599. ProceduralTexture.prototype.setFragment = function (fragment) {
  54600. this._fragment = fragment;
  54601. };
  54602. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  54603. get: function () {
  54604. return this._refreshRate;
  54605. },
  54606. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  54607. set: function (value) {
  54608. this._refreshRate = value;
  54609. this.resetRefreshCounter();
  54610. },
  54611. enumerable: true,
  54612. configurable: true
  54613. });
  54614. ProceduralTexture.prototype._shouldRender = function () {
  54615. if (!this.isEnabled || !this.isReady() || !this._texture) {
  54616. return false;
  54617. }
  54618. if (this._fallbackTextureUsed) {
  54619. return false;
  54620. }
  54621. if (this._currentRefreshId === -1) {
  54622. this._currentRefreshId = 1;
  54623. return true;
  54624. }
  54625. if (this.refreshRate === this._currentRefreshId) {
  54626. this._currentRefreshId = 1;
  54627. return true;
  54628. }
  54629. this._currentRefreshId++;
  54630. return false;
  54631. };
  54632. ProceduralTexture.prototype.getRenderSize = function () {
  54633. return this._size;
  54634. };
  54635. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  54636. if (this._fallbackTextureUsed) {
  54637. return;
  54638. }
  54639. this.releaseInternalTexture();
  54640. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  54641. };
  54642. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  54643. if (this._uniforms.indexOf(uniformName) === -1) {
  54644. this._uniforms.push(uniformName);
  54645. }
  54646. };
  54647. ProceduralTexture.prototype.setTexture = function (name, texture) {
  54648. if (this._samplers.indexOf(name) === -1) {
  54649. this._samplers.push(name);
  54650. }
  54651. this._textures[name] = texture;
  54652. return this;
  54653. };
  54654. ProceduralTexture.prototype.setFloat = function (name, value) {
  54655. this._checkUniform(name);
  54656. this._floats[name] = value;
  54657. return this;
  54658. };
  54659. ProceduralTexture.prototype.setFloats = function (name, value) {
  54660. this._checkUniform(name);
  54661. this._floatsArrays[name] = value;
  54662. return this;
  54663. };
  54664. ProceduralTexture.prototype.setColor3 = function (name, value) {
  54665. this._checkUniform(name);
  54666. this._colors3[name] = value;
  54667. return this;
  54668. };
  54669. ProceduralTexture.prototype.setColor4 = function (name, value) {
  54670. this._checkUniform(name);
  54671. this._colors4[name] = value;
  54672. return this;
  54673. };
  54674. ProceduralTexture.prototype.setVector2 = function (name, value) {
  54675. this._checkUniform(name);
  54676. this._vectors2[name] = value;
  54677. return this;
  54678. };
  54679. ProceduralTexture.prototype.setVector3 = function (name, value) {
  54680. this._checkUniform(name);
  54681. this._vectors3[name] = value;
  54682. return this;
  54683. };
  54684. ProceduralTexture.prototype.setMatrix = function (name, value) {
  54685. this._checkUniform(name);
  54686. this._matrices[name] = value;
  54687. return this;
  54688. };
  54689. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54690. var scene = this.getScene();
  54691. if (!scene) {
  54692. return;
  54693. }
  54694. var engine = this._engine;
  54695. // Render
  54696. engine.enableEffect(this._effect);
  54697. engine.setState(false);
  54698. // Texture
  54699. for (var name in this._textures) {
  54700. this._effect.setTexture(name, this._textures[name]);
  54701. }
  54702. // Float
  54703. for (name in this._floats) {
  54704. this._effect.setFloat(name, this._floats[name]);
  54705. }
  54706. // Floats
  54707. for (name in this._floatsArrays) {
  54708. this._effect.setArray(name, this._floatsArrays[name]);
  54709. }
  54710. // Color3
  54711. for (name in this._colors3) {
  54712. this._effect.setColor3(name, this._colors3[name]);
  54713. }
  54714. // Color4
  54715. for (name in this._colors4) {
  54716. var color = this._colors4[name];
  54717. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  54718. }
  54719. // Vector2
  54720. for (name in this._vectors2) {
  54721. this._effect.setVector2(name, this._vectors2[name]);
  54722. }
  54723. // Vector3
  54724. for (name in this._vectors3) {
  54725. this._effect.setVector3(name, this._vectors3[name]);
  54726. }
  54727. // Matrix
  54728. for (name in this._matrices) {
  54729. this._effect.setMatrix(name, this._matrices[name]);
  54730. }
  54731. if (!this._texture) {
  54732. return;
  54733. }
  54734. if (this.isCube) {
  54735. for (var face = 0; face < 6; face++) {
  54736. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  54737. // VBOs
  54738. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54739. this._effect.setFloat("face", face);
  54740. // Clear
  54741. engine.clear(scene.clearColor, true, true, true);
  54742. // Draw order
  54743. engine.draw(true, 0, 6);
  54744. // Mipmaps
  54745. if (face === 5) {
  54746. engine.generateMipMapsForCubemap(this._texture);
  54747. }
  54748. }
  54749. }
  54750. else {
  54751. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  54752. // VBOs
  54753. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54754. // Clear
  54755. engine.clear(scene.clearColor, true, true, true);
  54756. // Draw order
  54757. engine.draw(true, 0, 6);
  54758. }
  54759. // Unbind
  54760. engine.unBindFramebuffer(this._texture, this.isCube);
  54761. if (this.onGenerated) {
  54762. this.onGenerated();
  54763. }
  54764. };
  54765. ProceduralTexture.prototype.clone = function () {
  54766. var textureSize = this.getSize();
  54767. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  54768. // Base texture
  54769. newTexture.hasAlpha = this.hasAlpha;
  54770. newTexture.level = this.level;
  54771. // RenderTarget Texture
  54772. newTexture.coordinatesMode = this.coordinatesMode;
  54773. return newTexture;
  54774. };
  54775. ProceduralTexture.prototype.dispose = function () {
  54776. var scene = this.getScene();
  54777. if (!scene) {
  54778. return;
  54779. }
  54780. var index = scene._proceduralTextures.indexOf(this);
  54781. if (index >= 0) {
  54782. scene._proceduralTextures.splice(index, 1);
  54783. }
  54784. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54785. if (vertexBuffer) {
  54786. vertexBuffer.dispose();
  54787. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54788. }
  54789. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  54790. this._indexBuffer = null;
  54791. }
  54792. _super.prototype.dispose.call(this);
  54793. };
  54794. return ProceduralTexture;
  54795. }(BABYLON.Texture));
  54796. BABYLON.ProceduralTexture = ProceduralTexture;
  54797. })(BABYLON || (BABYLON = {}));
  54798. //# sourceMappingURL=babylon.proceduralTexture.js.map
  54799. var BABYLON;
  54800. (function (BABYLON) {
  54801. var CustomProceduralTexture = /** @class */ (function (_super) {
  54802. __extends(CustomProceduralTexture, _super);
  54803. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  54804. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  54805. _this._animate = true;
  54806. _this._time = 0;
  54807. _this._texturePath = texturePath;
  54808. //Try to load json
  54809. _this.loadJson(texturePath);
  54810. _this.refreshRate = 1;
  54811. return _this;
  54812. }
  54813. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  54814. var _this = this;
  54815. var noConfigFile = function () {
  54816. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  54817. try {
  54818. _this.setFragment(_this._texturePath);
  54819. }
  54820. catch (ex) {
  54821. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  54822. }
  54823. };
  54824. var configFileUrl = jsonUrl + "/config.json";
  54825. var xhr = new XMLHttpRequest();
  54826. xhr.open("GET", configFileUrl, true);
  54827. xhr.addEventListener("load", function () {
  54828. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  54829. try {
  54830. _this._config = JSON.parse(xhr.response);
  54831. _this.updateShaderUniforms();
  54832. _this.updateTextures();
  54833. _this.setFragment(_this._texturePath + "/custom");
  54834. _this._animate = _this._config.animate;
  54835. _this.refreshRate = _this._config.refreshrate;
  54836. }
  54837. catch (ex) {
  54838. noConfigFile();
  54839. }
  54840. }
  54841. else {
  54842. noConfigFile();
  54843. }
  54844. }, false);
  54845. xhr.addEventListener("error", function () {
  54846. noConfigFile();
  54847. }, false);
  54848. try {
  54849. xhr.send();
  54850. }
  54851. catch (ex) {
  54852. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  54853. }
  54854. };
  54855. CustomProceduralTexture.prototype.isReady = function () {
  54856. if (!_super.prototype.isReady.call(this)) {
  54857. return false;
  54858. }
  54859. for (var name in this._textures) {
  54860. var texture = this._textures[name];
  54861. if (!texture.isReady()) {
  54862. return false;
  54863. }
  54864. }
  54865. return true;
  54866. };
  54867. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  54868. var scene = this.getScene();
  54869. if (this._animate && scene) {
  54870. this._time += scene.getAnimationRatio() * 0.03;
  54871. this.updateShaderUniforms();
  54872. }
  54873. _super.prototype.render.call(this, useCameraPostProcess);
  54874. };
  54875. CustomProceduralTexture.prototype.updateTextures = function () {
  54876. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  54877. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  54878. }
  54879. };
  54880. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  54881. if (this._config) {
  54882. for (var j = 0; j < this._config.uniforms.length; j++) {
  54883. var uniform = this._config.uniforms[j];
  54884. switch (uniform.type) {
  54885. case "float":
  54886. this.setFloat(uniform.name, uniform.value);
  54887. break;
  54888. case "color3":
  54889. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  54890. break;
  54891. case "color4":
  54892. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  54893. break;
  54894. case "vector2":
  54895. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  54896. break;
  54897. case "vector3":
  54898. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  54899. break;
  54900. }
  54901. }
  54902. }
  54903. this.setFloat("time", this._time);
  54904. };
  54905. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  54906. get: function () {
  54907. return this._animate;
  54908. },
  54909. set: function (value) {
  54910. this._animate = value;
  54911. },
  54912. enumerable: true,
  54913. configurable: true
  54914. });
  54915. return CustomProceduralTexture;
  54916. }(BABYLON.ProceduralTexture));
  54917. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  54918. })(BABYLON || (BABYLON = {}));
  54919. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  54920. var BABYLON;
  54921. (function (BABYLON) {
  54922. var FreeCameraGamepadInput = /** @class */ (function () {
  54923. function FreeCameraGamepadInput() {
  54924. this.gamepadAngularSensibility = 200;
  54925. this.gamepadMoveSensibility = 40;
  54926. // private members
  54927. this._cameraTransform = BABYLON.Matrix.Identity();
  54928. this._deltaTransform = BABYLON.Vector3.Zero();
  54929. this._vector3 = BABYLON.Vector3.Zero();
  54930. this._vector2 = BABYLON.Vector2.Zero();
  54931. }
  54932. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  54933. var _this = this;
  54934. var manager = this.camera.getScene().gamepadManager;
  54935. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  54936. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  54937. // prioritize XBOX gamepads.
  54938. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  54939. _this.gamepad = gamepad;
  54940. }
  54941. }
  54942. });
  54943. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  54944. if (_this.gamepad === gamepad) {
  54945. _this.gamepad = null;
  54946. }
  54947. });
  54948. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  54949. };
  54950. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  54951. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  54952. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  54953. this.gamepad = null;
  54954. };
  54955. FreeCameraGamepadInput.prototype.checkInputs = function () {
  54956. if (this.gamepad && this.gamepad.leftStick) {
  54957. var camera = this.camera;
  54958. var LSValues = this.gamepad.leftStick;
  54959. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  54960. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  54961. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  54962. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  54963. var RSValues = this.gamepad.rightStick;
  54964. if (RSValues) {
  54965. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  54966. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  54967. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  54968. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  54969. }
  54970. else {
  54971. RSValues = { x: 0, y: 0 };
  54972. }
  54973. if (!camera.rotationQuaternion) {
  54974. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  54975. }
  54976. else {
  54977. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  54978. }
  54979. var speed = camera._computeLocalCameraSpeed() * 50.0;
  54980. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  54981. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  54982. camera.cameraDirection.addInPlace(this._deltaTransform);
  54983. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  54984. camera.cameraRotation.addInPlace(this._vector2);
  54985. }
  54986. };
  54987. FreeCameraGamepadInput.prototype.getClassName = function () {
  54988. return "FreeCameraGamepadInput";
  54989. };
  54990. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  54991. return "gamepad";
  54992. };
  54993. __decorate([
  54994. BABYLON.serialize()
  54995. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  54996. __decorate([
  54997. BABYLON.serialize()
  54998. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  54999. return FreeCameraGamepadInput;
  55000. }());
  55001. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  55002. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  55003. })(BABYLON || (BABYLON = {}));
  55004. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  55005. var BABYLON;
  55006. (function (BABYLON) {
  55007. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  55008. function ArcRotateCameraGamepadInput() {
  55009. this.gamepadRotationSensibility = 80;
  55010. this.gamepadMoveSensibility = 40;
  55011. }
  55012. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  55013. var _this = this;
  55014. var manager = this.camera.getScene().gamepadManager;
  55015. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  55016. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  55017. // prioritize XBOX gamepads.
  55018. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  55019. _this.gamepad = gamepad;
  55020. }
  55021. }
  55022. });
  55023. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  55024. if (_this.gamepad === gamepad) {
  55025. _this.gamepad = null;
  55026. }
  55027. });
  55028. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  55029. };
  55030. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  55031. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  55032. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  55033. this.gamepad = null;
  55034. };
  55035. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  55036. if (this.gamepad) {
  55037. var camera = this.camera;
  55038. var RSValues = this.gamepad.rightStick;
  55039. if (RSValues) {
  55040. if (RSValues.x != 0) {
  55041. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  55042. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  55043. camera.inertialAlphaOffset += normalizedRX;
  55044. }
  55045. }
  55046. if (RSValues.y != 0) {
  55047. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  55048. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  55049. camera.inertialBetaOffset += normalizedRY;
  55050. }
  55051. }
  55052. }
  55053. var LSValues = this.gamepad.leftStick;
  55054. if (LSValues && LSValues.y != 0) {
  55055. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  55056. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  55057. this.camera.inertialRadiusOffset -= normalizedLY;
  55058. }
  55059. }
  55060. }
  55061. };
  55062. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  55063. return "ArcRotateCameraGamepadInput";
  55064. };
  55065. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  55066. return "gamepad";
  55067. };
  55068. __decorate([
  55069. BABYLON.serialize()
  55070. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  55071. __decorate([
  55072. BABYLON.serialize()
  55073. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  55074. return ArcRotateCameraGamepadInput;
  55075. }());
  55076. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  55077. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  55078. })(BABYLON || (BABYLON = {}));
  55079. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  55080. var BABYLON;
  55081. (function (BABYLON) {
  55082. var GamepadManager = /** @class */ (function () {
  55083. function GamepadManager() {
  55084. var _this = this;
  55085. this._babylonGamepads = [];
  55086. this._oneGamepadConnected = false;
  55087. this._isMonitoring = false;
  55088. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  55089. if (!BABYLON.Tools.IsWindowObjectExist()) {
  55090. this._gamepadEventSupported = false;
  55091. }
  55092. else {
  55093. this._gamepadEventSupported = 'GamepadEvent' in window;
  55094. this._gamepadSupport = (navigator.getGamepads ||
  55095. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  55096. }
  55097. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  55098. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  55099. for (var i in _this._babylonGamepads) {
  55100. var gamepad = _this._babylonGamepads[i];
  55101. if (gamepad && gamepad._isConnected) {
  55102. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  55103. }
  55104. }
  55105. });
  55106. this._onGamepadConnectedEvent = function (evt) {
  55107. var gamepad = evt.gamepad;
  55108. if (gamepad.index in _this._babylonGamepads) {
  55109. if (_this._babylonGamepads[gamepad.index].isConnected) {
  55110. return;
  55111. }
  55112. }
  55113. var newGamepad;
  55114. if (_this._babylonGamepads[gamepad.index]) {
  55115. newGamepad = _this._babylonGamepads[gamepad.index];
  55116. newGamepad.browserGamepad = gamepad;
  55117. newGamepad._isConnected = true;
  55118. }
  55119. else {
  55120. newGamepad = _this._addNewGamepad(gamepad);
  55121. }
  55122. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55123. _this._startMonitoringGamepads();
  55124. };
  55125. this._onGamepadDisconnectedEvent = function (evt) {
  55126. var gamepad = evt.gamepad;
  55127. // Remove the gamepad from the list of gamepads to monitor.
  55128. for (var i in _this._babylonGamepads) {
  55129. if (_this._babylonGamepads[i].index === gamepad.index) {
  55130. var disconnectedGamepad = _this._babylonGamepads[i];
  55131. disconnectedGamepad._isConnected = false;
  55132. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  55133. break;
  55134. }
  55135. }
  55136. };
  55137. if (this._gamepadSupport) {
  55138. //first add already-connected gamepads
  55139. this._updateGamepadObjects();
  55140. if (this._babylonGamepads.length) {
  55141. this._startMonitoringGamepads();
  55142. }
  55143. // Checking if the gamepad connected event is supported (like in Firefox)
  55144. if (this._gamepadEventSupported) {
  55145. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  55146. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  55147. }
  55148. else {
  55149. this._startMonitoringGamepads();
  55150. }
  55151. }
  55152. }
  55153. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  55154. get: function () {
  55155. return this._babylonGamepads;
  55156. },
  55157. enumerable: true,
  55158. configurable: true
  55159. });
  55160. GamepadManager.prototype.getGamepadByType = function (type) {
  55161. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  55162. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  55163. var gamepad = _a[_i];
  55164. if (gamepad && gamepad.type === type) {
  55165. return gamepad;
  55166. }
  55167. }
  55168. return null;
  55169. };
  55170. GamepadManager.prototype.dispose = function () {
  55171. if (this._gamepadEventSupported) {
  55172. if (this._onGamepadConnectedEvent) {
  55173. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  55174. }
  55175. if (this._onGamepadDisconnectedEvent) {
  55176. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  55177. }
  55178. this._onGamepadConnectedEvent = null;
  55179. this._onGamepadDisconnectedEvent = null;
  55180. }
  55181. this._babylonGamepads.forEach(function (gamepad) {
  55182. gamepad.dispose();
  55183. });
  55184. this.onGamepadConnectedObservable.clear();
  55185. this.onGamepadDisconnectedObservable.clear();
  55186. this._oneGamepadConnected = false;
  55187. this._stopMonitoringGamepads();
  55188. this._babylonGamepads = [];
  55189. };
  55190. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  55191. if (!this._oneGamepadConnected) {
  55192. this._oneGamepadConnected = true;
  55193. }
  55194. var newGamepad;
  55195. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  55196. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  55197. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  55198. }
  55199. else if (gamepad.pose) {
  55200. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  55201. }
  55202. else {
  55203. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  55204. }
  55205. this._babylonGamepads[newGamepad.index] = newGamepad;
  55206. return newGamepad;
  55207. };
  55208. GamepadManager.prototype._startMonitoringGamepads = function () {
  55209. if (!this._isMonitoring) {
  55210. this._isMonitoring = true;
  55211. this._checkGamepadsStatus();
  55212. }
  55213. };
  55214. GamepadManager.prototype._stopMonitoringGamepads = function () {
  55215. this._isMonitoring = false;
  55216. };
  55217. GamepadManager.prototype._checkGamepadsStatus = function () {
  55218. var _this = this;
  55219. // Hack to be compatible Chrome
  55220. this._updateGamepadObjects();
  55221. for (var i in this._babylonGamepads) {
  55222. var gamepad = this._babylonGamepads[i];
  55223. if (!gamepad || !gamepad.isConnected) {
  55224. continue;
  55225. }
  55226. gamepad.update();
  55227. }
  55228. if (this._isMonitoring) {
  55229. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  55230. }
  55231. };
  55232. // This function is called only on Chrome, which does not properly support
  55233. // connection/disconnection events and forces you to recopy again the gamepad object
  55234. GamepadManager.prototype._updateGamepadObjects = function () {
  55235. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  55236. for (var i = 0; i < gamepads.length; i++) {
  55237. if (gamepads[i]) {
  55238. if (!this._babylonGamepads[gamepads[i].index]) {
  55239. var newGamepad = this._addNewGamepad(gamepads[i]);
  55240. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  55241. }
  55242. else {
  55243. // Forced to copy again this object for Chrome for unknown reason
  55244. this._babylonGamepads[i].browserGamepad = gamepads[i];
  55245. if (!this._babylonGamepads[i].isConnected) {
  55246. this._babylonGamepads[i]._isConnected = true;
  55247. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  55248. }
  55249. }
  55250. }
  55251. }
  55252. };
  55253. return GamepadManager;
  55254. }());
  55255. BABYLON.GamepadManager = GamepadManager;
  55256. })(BABYLON || (BABYLON = {}));
  55257. //# sourceMappingURL=babylon.gamepadManager.js.map
  55258. var BABYLON;
  55259. (function (BABYLON) {
  55260. var StickValues = /** @class */ (function () {
  55261. function StickValues(x, y) {
  55262. this.x = x;
  55263. this.y = y;
  55264. }
  55265. return StickValues;
  55266. }());
  55267. BABYLON.StickValues = StickValues;
  55268. var Gamepad = /** @class */ (function () {
  55269. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  55270. if (leftStickX === void 0) { leftStickX = 0; }
  55271. if (leftStickY === void 0) { leftStickY = 1; }
  55272. if (rightStickX === void 0) { rightStickX = 2; }
  55273. if (rightStickY === void 0) { rightStickY = 3; }
  55274. this.id = id;
  55275. this.index = index;
  55276. this.browserGamepad = browserGamepad;
  55277. this._isConnected = true;
  55278. this.type = Gamepad.GAMEPAD;
  55279. this._leftStickAxisX = leftStickX;
  55280. this._leftStickAxisY = leftStickY;
  55281. this._rightStickAxisX = rightStickX;
  55282. this._rightStickAxisY = rightStickY;
  55283. if (this.browserGamepad.axes.length >= 2) {
  55284. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55285. }
  55286. if (this.browserGamepad.axes.length >= 4) {
  55287. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55288. }
  55289. }
  55290. Object.defineProperty(Gamepad.prototype, "isConnected", {
  55291. get: function () {
  55292. return this._isConnected;
  55293. },
  55294. enumerable: true,
  55295. configurable: true
  55296. });
  55297. Gamepad.prototype.onleftstickchanged = function (callback) {
  55298. this._onleftstickchanged = callback;
  55299. };
  55300. Gamepad.prototype.onrightstickchanged = function (callback) {
  55301. this._onrightstickchanged = callback;
  55302. };
  55303. Object.defineProperty(Gamepad.prototype, "leftStick", {
  55304. get: function () {
  55305. return this._leftStick;
  55306. },
  55307. set: function (newValues) {
  55308. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  55309. this._onleftstickchanged(newValues);
  55310. }
  55311. this._leftStick = newValues;
  55312. },
  55313. enumerable: true,
  55314. configurable: true
  55315. });
  55316. Object.defineProperty(Gamepad.prototype, "rightStick", {
  55317. get: function () {
  55318. return this._rightStick;
  55319. },
  55320. set: function (newValues) {
  55321. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  55322. this._onrightstickchanged(newValues);
  55323. }
  55324. this._rightStick = newValues;
  55325. },
  55326. enumerable: true,
  55327. configurable: true
  55328. });
  55329. Gamepad.prototype.update = function () {
  55330. if (this._leftStick) {
  55331. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  55332. }
  55333. if (this._rightStick) {
  55334. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  55335. }
  55336. };
  55337. Gamepad.prototype.dispose = function () {
  55338. };
  55339. Gamepad.GAMEPAD = 0;
  55340. Gamepad.GENERIC = 1;
  55341. Gamepad.XBOX = 2;
  55342. Gamepad.POSE_ENABLED = 3;
  55343. return Gamepad;
  55344. }());
  55345. BABYLON.Gamepad = Gamepad;
  55346. var GenericPad = /** @class */ (function (_super) {
  55347. __extends(GenericPad, _super);
  55348. function GenericPad(id, index, browserGamepad) {
  55349. var _this = _super.call(this, id, index, browserGamepad) || this;
  55350. _this.onButtonDownObservable = new BABYLON.Observable();
  55351. _this.onButtonUpObservable = new BABYLON.Observable();
  55352. _this.type = Gamepad.GENERIC;
  55353. _this._buttons = new Array(browserGamepad.buttons.length);
  55354. return _this;
  55355. }
  55356. GenericPad.prototype.onbuttondown = function (callback) {
  55357. this._onbuttondown = callback;
  55358. };
  55359. GenericPad.prototype.onbuttonup = function (callback) {
  55360. this._onbuttonup = callback;
  55361. };
  55362. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  55363. if (newValue !== currentValue) {
  55364. if (newValue === 1) {
  55365. if (this._onbuttondown) {
  55366. this._onbuttondown(buttonIndex);
  55367. }
  55368. this.onButtonDownObservable.notifyObservers(buttonIndex);
  55369. }
  55370. if (newValue === 0) {
  55371. if (this._onbuttonup) {
  55372. this._onbuttonup(buttonIndex);
  55373. }
  55374. this.onButtonUpObservable.notifyObservers(buttonIndex);
  55375. }
  55376. }
  55377. return newValue;
  55378. };
  55379. GenericPad.prototype.update = function () {
  55380. _super.prototype.update.call(this);
  55381. for (var index = 0; index < this._buttons.length; index++) {
  55382. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  55383. }
  55384. };
  55385. return GenericPad;
  55386. }(Gamepad));
  55387. BABYLON.GenericPad = GenericPad;
  55388. })(BABYLON || (BABYLON = {}));
  55389. //# sourceMappingURL=babylon.gamepad.js.map
  55390. var BABYLON;
  55391. (function (BABYLON) {
  55392. var Xbox360Button;
  55393. (function (Xbox360Button) {
  55394. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  55395. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  55396. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  55397. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  55398. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  55399. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  55400. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  55401. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  55402. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  55403. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  55404. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  55405. var Xbox360Dpad;
  55406. (function (Xbox360Dpad) {
  55407. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  55408. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  55409. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  55410. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  55411. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  55412. var Xbox360Pad = /** @class */ (function (_super) {
  55413. __extends(Xbox360Pad, _super);
  55414. function Xbox360Pad(id, index, gamepad, xboxOne) {
  55415. if (xboxOne === void 0) { xboxOne = false; }
  55416. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  55417. _this._leftTrigger = 0;
  55418. _this._rightTrigger = 0;
  55419. _this.onButtonDownObservable = new BABYLON.Observable();
  55420. _this.onButtonUpObservable = new BABYLON.Observable();
  55421. _this.onPadDownObservable = new BABYLON.Observable();
  55422. _this.onPadUpObservable = new BABYLON.Observable();
  55423. _this._buttonA = 0;
  55424. _this._buttonB = 0;
  55425. _this._buttonX = 0;
  55426. _this._buttonY = 0;
  55427. _this._buttonBack = 0;
  55428. _this._buttonStart = 0;
  55429. _this._buttonLB = 0;
  55430. _this._buttonRB = 0;
  55431. _this._buttonLeftStick = 0;
  55432. _this._buttonRightStick = 0;
  55433. _this._dPadUp = 0;
  55434. _this._dPadDown = 0;
  55435. _this._dPadLeft = 0;
  55436. _this._dPadRight = 0;
  55437. _this._isXboxOnePad = false;
  55438. _this.type = BABYLON.Gamepad.XBOX;
  55439. _this._isXboxOnePad = xboxOne;
  55440. return _this;
  55441. }
  55442. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  55443. this._onlefttriggerchanged = callback;
  55444. };
  55445. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  55446. this._onrighttriggerchanged = callback;
  55447. };
  55448. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  55449. get: function () {
  55450. return this._leftTrigger;
  55451. },
  55452. set: function (newValue) {
  55453. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  55454. this._onlefttriggerchanged(newValue);
  55455. }
  55456. this._leftTrigger = newValue;
  55457. },
  55458. enumerable: true,
  55459. configurable: true
  55460. });
  55461. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  55462. get: function () {
  55463. return this._rightTrigger;
  55464. },
  55465. set: function (newValue) {
  55466. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  55467. this._onrighttriggerchanged(newValue);
  55468. }
  55469. this._rightTrigger = newValue;
  55470. },
  55471. enumerable: true,
  55472. configurable: true
  55473. });
  55474. Xbox360Pad.prototype.onbuttondown = function (callback) {
  55475. this._onbuttondown = callback;
  55476. };
  55477. Xbox360Pad.prototype.onbuttonup = function (callback) {
  55478. this._onbuttonup = callback;
  55479. };
  55480. Xbox360Pad.prototype.ondpaddown = function (callback) {
  55481. this._ondpaddown = callback;
  55482. };
  55483. Xbox360Pad.prototype.ondpadup = function (callback) {
  55484. this._ondpadup = callback;
  55485. };
  55486. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  55487. if (newValue !== currentValue) {
  55488. if (newValue === 1) {
  55489. if (this._onbuttondown) {
  55490. this._onbuttondown(buttonType);
  55491. }
  55492. this.onButtonDownObservable.notifyObservers(buttonType);
  55493. }
  55494. if (newValue === 0) {
  55495. if (this._onbuttonup) {
  55496. this._onbuttonup(buttonType);
  55497. }
  55498. this.onButtonUpObservable.notifyObservers(buttonType);
  55499. }
  55500. }
  55501. return newValue;
  55502. };
  55503. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  55504. if (newValue !== currentValue) {
  55505. if (newValue === 1) {
  55506. if (this._ondpaddown) {
  55507. this._ondpaddown(buttonType);
  55508. }
  55509. this.onPadDownObservable.notifyObservers(buttonType);
  55510. }
  55511. if (newValue === 0) {
  55512. if (this._ondpadup) {
  55513. this._ondpadup(buttonType);
  55514. }
  55515. this.onPadUpObservable.notifyObservers(buttonType);
  55516. }
  55517. }
  55518. return newValue;
  55519. };
  55520. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  55521. get: function () {
  55522. return this._buttonA;
  55523. },
  55524. set: function (value) {
  55525. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  55526. },
  55527. enumerable: true,
  55528. configurable: true
  55529. });
  55530. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  55531. get: function () {
  55532. return this._buttonB;
  55533. },
  55534. set: function (value) {
  55535. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  55536. },
  55537. enumerable: true,
  55538. configurable: true
  55539. });
  55540. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  55541. get: function () {
  55542. return this._buttonX;
  55543. },
  55544. set: function (value) {
  55545. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  55546. },
  55547. enumerable: true,
  55548. configurable: true
  55549. });
  55550. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  55551. get: function () {
  55552. return this._buttonY;
  55553. },
  55554. set: function (value) {
  55555. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  55556. },
  55557. enumerable: true,
  55558. configurable: true
  55559. });
  55560. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  55561. get: function () {
  55562. return this._buttonStart;
  55563. },
  55564. set: function (value) {
  55565. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  55566. },
  55567. enumerable: true,
  55568. configurable: true
  55569. });
  55570. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  55571. get: function () {
  55572. return this._buttonBack;
  55573. },
  55574. set: function (value) {
  55575. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  55576. },
  55577. enumerable: true,
  55578. configurable: true
  55579. });
  55580. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  55581. get: function () {
  55582. return this._buttonLB;
  55583. },
  55584. set: function (value) {
  55585. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  55586. },
  55587. enumerable: true,
  55588. configurable: true
  55589. });
  55590. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  55591. get: function () {
  55592. return this._buttonRB;
  55593. },
  55594. set: function (value) {
  55595. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  55596. },
  55597. enumerable: true,
  55598. configurable: true
  55599. });
  55600. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  55601. get: function () {
  55602. return this._buttonLeftStick;
  55603. },
  55604. set: function (value) {
  55605. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  55606. },
  55607. enumerable: true,
  55608. configurable: true
  55609. });
  55610. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  55611. get: function () {
  55612. return this._buttonRightStick;
  55613. },
  55614. set: function (value) {
  55615. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  55616. },
  55617. enumerable: true,
  55618. configurable: true
  55619. });
  55620. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  55621. get: function () {
  55622. return this._dPadUp;
  55623. },
  55624. set: function (value) {
  55625. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  55626. },
  55627. enumerable: true,
  55628. configurable: true
  55629. });
  55630. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  55631. get: function () {
  55632. return this._dPadDown;
  55633. },
  55634. set: function (value) {
  55635. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  55636. },
  55637. enumerable: true,
  55638. configurable: true
  55639. });
  55640. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  55641. get: function () {
  55642. return this._dPadLeft;
  55643. },
  55644. set: function (value) {
  55645. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  55646. },
  55647. enumerable: true,
  55648. configurable: true
  55649. });
  55650. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  55651. get: function () {
  55652. return this._dPadRight;
  55653. },
  55654. set: function (value) {
  55655. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  55656. },
  55657. enumerable: true,
  55658. configurable: true
  55659. });
  55660. Xbox360Pad.prototype.update = function () {
  55661. _super.prototype.update.call(this);
  55662. if (this._isXboxOnePad) {
  55663. this.buttonA = this.browserGamepad.buttons[0].value;
  55664. this.buttonB = this.browserGamepad.buttons[1].value;
  55665. this.buttonX = this.browserGamepad.buttons[2].value;
  55666. this.buttonY = this.browserGamepad.buttons[3].value;
  55667. this.buttonLB = this.browserGamepad.buttons[4].value;
  55668. this.buttonRB = this.browserGamepad.buttons[5].value;
  55669. this.leftTrigger = this.browserGamepad.axes[2];
  55670. this.rightTrigger = this.browserGamepad.axes[5];
  55671. this.buttonBack = this.browserGamepad.buttons[9].value;
  55672. this.buttonStart = this.browserGamepad.buttons[8].value;
  55673. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  55674. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  55675. this.dPadUp = this.browserGamepad.buttons[11].value;
  55676. this.dPadDown = this.browserGamepad.buttons[12].value;
  55677. this.dPadLeft = this.browserGamepad.buttons[13].value;
  55678. this.dPadRight = this.browserGamepad.buttons[14].value;
  55679. }
  55680. else {
  55681. this.buttonA = this.browserGamepad.buttons[0].value;
  55682. this.buttonB = this.browserGamepad.buttons[1].value;
  55683. this.buttonX = this.browserGamepad.buttons[2].value;
  55684. this.buttonY = this.browserGamepad.buttons[3].value;
  55685. this.buttonLB = this.browserGamepad.buttons[4].value;
  55686. this.buttonRB = this.browserGamepad.buttons[5].value;
  55687. this.leftTrigger = this.browserGamepad.buttons[6].value;
  55688. this.rightTrigger = this.browserGamepad.buttons[7].value;
  55689. this.buttonBack = this.browserGamepad.buttons[8].value;
  55690. this.buttonStart = this.browserGamepad.buttons[9].value;
  55691. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  55692. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  55693. this.dPadUp = this.browserGamepad.buttons[12].value;
  55694. this.dPadDown = this.browserGamepad.buttons[13].value;
  55695. this.dPadLeft = this.browserGamepad.buttons[14].value;
  55696. this.dPadRight = this.browserGamepad.buttons[15].value;
  55697. }
  55698. };
  55699. return Xbox360Pad;
  55700. }(BABYLON.Gamepad));
  55701. BABYLON.Xbox360Pad = Xbox360Pad;
  55702. })(BABYLON || (BABYLON = {}));
  55703. //# sourceMappingURL=babylon.xboxGamepad.js.map
  55704. var BABYLON;
  55705. (function (BABYLON) {
  55706. var PoseEnabledControllerType;
  55707. (function (PoseEnabledControllerType) {
  55708. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  55709. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  55710. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  55711. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  55712. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  55713. var PoseEnabledControllerHelper = /** @class */ (function () {
  55714. function PoseEnabledControllerHelper() {
  55715. }
  55716. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  55717. // Oculus Touch
  55718. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  55719. return new BABYLON.OculusTouchController(vrGamepad);
  55720. }
  55721. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  55722. return new BABYLON.WindowsMotionController(vrGamepad);
  55723. }
  55724. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  55725. return new BABYLON.ViveController(vrGamepad);
  55726. }
  55727. else {
  55728. return new BABYLON.GenericController(vrGamepad);
  55729. }
  55730. };
  55731. return PoseEnabledControllerHelper;
  55732. }());
  55733. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  55734. var PoseEnabledController = /** @class */ (function (_super) {
  55735. __extends(PoseEnabledController, _super);
  55736. function PoseEnabledController(browserGamepad) {
  55737. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  55738. _this.deviceScaleFactor = 1;
  55739. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  55740. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  55741. _this.controllerType = PoseEnabledControllerType.GENERIC;
  55742. _this.position = BABYLON.Vector3.Zero();
  55743. _this.rotationQuaternion = new BABYLON.Quaternion();
  55744. _this.devicePosition = BABYLON.Vector3.Zero();
  55745. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  55746. _this._calculatedPosition = BABYLON.Vector3.Zero();
  55747. _this._calculatedRotation = new BABYLON.Quaternion();
  55748. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  55749. return _this;
  55750. }
  55751. PoseEnabledController.prototype.update = function () {
  55752. _super.prototype.update.call(this);
  55753. var pose = this.browserGamepad.pose;
  55754. this.updateFromDevice(pose);
  55755. if (this._mesh) {
  55756. this._mesh.position.copyFrom(this._calculatedPosition);
  55757. if (this._mesh.rotationQuaternion) {
  55758. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  55759. }
  55760. }
  55761. };
  55762. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  55763. if (poseData) {
  55764. this.rawPose = poseData;
  55765. if (poseData.position) {
  55766. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  55767. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  55768. this.devicePosition.z *= -1;
  55769. }
  55770. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  55771. this._calculatedPosition.addInPlace(this.position);
  55772. }
  55773. var pose = this.rawPose;
  55774. if (poseData.orientation && pose.orientation) {
  55775. this.deviceRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  55776. if (this._mesh) {
  55777. if (this._mesh.getScene().useRightHandedSystem) {
  55778. this.deviceRotationQuaternion.z *= -1;
  55779. this.deviceRotationQuaternion.w *= -1;
  55780. }
  55781. else {
  55782. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  55783. }
  55784. }
  55785. // if the camera is set, rotate to the camera's rotation
  55786. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  55787. }
  55788. }
  55789. };
  55790. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  55791. if (this._mesh) {
  55792. this._mesh.parent = null;
  55793. }
  55794. this._mesh = mesh;
  55795. if (this._poseControlledCamera) {
  55796. this._mesh.parent = this._poseControlledCamera;
  55797. }
  55798. if (!this._mesh.rotationQuaternion) {
  55799. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  55800. }
  55801. };
  55802. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  55803. this._poseControlledCamera = camera;
  55804. if (this._mesh) {
  55805. this._mesh.parent = this._poseControlledCamera;
  55806. }
  55807. };
  55808. PoseEnabledController.prototype.dispose = function () {
  55809. if (this._mesh) {
  55810. this._mesh.dispose();
  55811. }
  55812. this._mesh = null;
  55813. _super.prototype.dispose.call(this);
  55814. };
  55815. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  55816. get: function () {
  55817. return this._mesh;
  55818. },
  55819. enumerable: true,
  55820. configurable: true
  55821. });
  55822. PoseEnabledController.prototype.getForwardRay = function (length) {
  55823. if (length === void 0) { length = 100; }
  55824. if (!this.mesh) {
  55825. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  55826. }
  55827. var m = this.mesh.getWorldMatrix();
  55828. var origin = m.getTranslation();
  55829. var forward = new BABYLON.Vector3(0, 0, -1);
  55830. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  55831. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  55832. return new BABYLON.Ray(origin, direction, length);
  55833. };
  55834. return PoseEnabledController;
  55835. }(BABYLON.Gamepad));
  55836. BABYLON.PoseEnabledController = PoseEnabledController;
  55837. })(BABYLON || (BABYLON = {}));
  55838. //# sourceMappingURL=babylon.poseEnabledController.js.map
  55839. var BABYLON;
  55840. (function (BABYLON) {
  55841. var WebVRController = /** @class */ (function (_super) {
  55842. __extends(WebVRController, _super);
  55843. function WebVRController(vrGamepad) {
  55844. var _this = _super.call(this, vrGamepad) || this;
  55845. // Observables
  55846. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  55847. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  55848. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  55849. _this.onPadStateChangedObservable = new BABYLON.Observable();
  55850. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  55851. _this.pad = { x: 0, y: 0 };
  55852. // avoid GC, store state in a tmp object
  55853. _this._changes = {
  55854. pressChanged: false,
  55855. touchChanged: false,
  55856. valueChanged: false,
  55857. changed: false
  55858. };
  55859. _this._buttons = new Array(vrGamepad.buttons.length);
  55860. _this.hand = vrGamepad.hand;
  55861. return _this;
  55862. }
  55863. WebVRController.prototype.onButtonStateChange = function (callback) {
  55864. this._onButtonStateChange = callback;
  55865. };
  55866. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  55867. get: function () {
  55868. return this._defaultModel;
  55869. },
  55870. enumerable: true,
  55871. configurable: true
  55872. });
  55873. WebVRController.prototype.update = function () {
  55874. _super.prototype.update.call(this);
  55875. for (var index = 0; index < this._buttons.length; index++) {
  55876. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  55877. }
  55878. ;
  55879. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  55880. this.pad.x = this.leftStick.x;
  55881. this.pad.y = this.leftStick.y;
  55882. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  55883. }
  55884. };
  55885. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  55886. if (!newState) {
  55887. newState = {
  55888. pressed: false,
  55889. touched: false,
  55890. value: 0
  55891. };
  55892. }
  55893. if (!currentState) {
  55894. this._buttons[buttonIndex] = {
  55895. pressed: newState.pressed,
  55896. touched: newState.touched,
  55897. value: newState.value
  55898. };
  55899. return;
  55900. }
  55901. this._checkChanges(newState, currentState);
  55902. if (this._changes.changed) {
  55903. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  55904. this.handleButtonChange(buttonIndex, newState, this._changes);
  55905. }
  55906. this._buttons[buttonIndex].pressed = newState.pressed;
  55907. this._buttons[buttonIndex].touched = newState.touched;
  55908. // oculus triggers are never 0, thou not touched.
  55909. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  55910. };
  55911. WebVRController.prototype._checkChanges = function (newState, currentState) {
  55912. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  55913. this._changes.touchChanged = newState.touched !== currentState.touched;
  55914. this._changes.valueChanged = newState.value !== currentState.value;
  55915. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  55916. return this._changes;
  55917. };
  55918. WebVRController.prototype.dispose = function () {
  55919. _super.prototype.dispose.call(this);
  55920. this.onTriggerStateChangedObservable.clear();
  55921. this.onMainButtonStateChangedObservable.clear();
  55922. this.onSecondaryButtonStateChangedObservable.clear();
  55923. this.onPadStateChangedObservable.clear();
  55924. this.onPadValuesChangedObservable.clear();
  55925. };
  55926. return WebVRController;
  55927. }(BABYLON.PoseEnabledController));
  55928. BABYLON.WebVRController = WebVRController;
  55929. })(BABYLON || (BABYLON = {}));
  55930. //# sourceMappingURL=babylon.webVRController.js.map
  55931. var BABYLON;
  55932. (function (BABYLON) {
  55933. var OculusTouchController = /** @class */ (function (_super) {
  55934. __extends(OculusTouchController, _super);
  55935. function OculusTouchController(vrGamepad) {
  55936. var _this = _super.call(this, vrGamepad) || this;
  55937. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  55938. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  55939. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  55940. return _this;
  55941. }
  55942. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  55943. var _this = this;
  55944. var meshName;
  55945. // Hand
  55946. if (this.hand === 'left') {
  55947. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  55948. }
  55949. else {
  55950. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  55951. }
  55952. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  55953. /*
  55954. Parent Mesh name: oculus_touch_left
  55955. - body
  55956. - trigger
  55957. - thumbstick
  55958. - grip
  55959. - button_y
  55960. - button_x
  55961. - button_enter
  55962. */
  55963. _this._defaultModel = newMeshes[1];
  55964. _this.attachToMesh(_this._defaultModel);
  55965. if (meshLoaded) {
  55966. meshLoaded(_this._defaultModel);
  55967. }
  55968. });
  55969. };
  55970. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  55971. // helper getters for left and right hand.
  55972. get: function () {
  55973. if (this.hand === 'right') {
  55974. return this.onMainButtonStateChangedObservable;
  55975. }
  55976. else {
  55977. throw new Error('No A button on left hand');
  55978. }
  55979. },
  55980. enumerable: true,
  55981. configurable: true
  55982. });
  55983. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  55984. get: function () {
  55985. if (this.hand === 'right') {
  55986. return this.onSecondaryButtonStateChangedObservable;
  55987. }
  55988. else {
  55989. throw new Error('No B button on left hand');
  55990. }
  55991. },
  55992. enumerable: true,
  55993. configurable: true
  55994. });
  55995. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  55996. get: function () {
  55997. if (this.hand === 'left') {
  55998. return this.onMainButtonStateChangedObservable;
  55999. }
  56000. else {
  56001. throw new Error('No X button on right hand');
  56002. }
  56003. },
  56004. enumerable: true,
  56005. configurable: true
  56006. });
  56007. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  56008. get: function () {
  56009. if (this.hand === 'left') {
  56010. return this.onSecondaryButtonStateChangedObservable;
  56011. }
  56012. else {
  56013. throw new Error('No Y button on right hand');
  56014. }
  56015. },
  56016. enumerable: true,
  56017. configurable: true
  56018. });
  56019. /*
  56020. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  56021. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  56022. 2) secondary trigger (same)
  56023. 3) A (right) X (left), touch, pressed = value
  56024. 4) B / Y
  56025. 5) thumb rest
  56026. */
  56027. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56028. var notifyObject = state; //{ state: state, changes: changes };
  56029. var triggerDirection = this.hand === 'right' ? -1 : 1;
  56030. switch (buttonIdx) {
  56031. case 0:
  56032. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56033. return;
  56034. case 1:// index trigger
  56035. if (this._defaultModel) {
  56036. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  56037. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  56038. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  56039. }
  56040. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56041. return;
  56042. case 2:// secondary trigger
  56043. if (this._defaultModel) {
  56044. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  56045. }
  56046. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  56047. return;
  56048. case 3:
  56049. if (this._defaultModel) {
  56050. if (notifyObject.pressed) {
  56051. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  56052. }
  56053. else {
  56054. (this._defaultModel.getChildren()[1]).position.y = 0;
  56055. }
  56056. }
  56057. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56058. return;
  56059. case 4:
  56060. if (this._defaultModel) {
  56061. if (notifyObject.pressed) {
  56062. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56063. }
  56064. else {
  56065. (this._defaultModel.getChildren()[2]).position.y = 0;
  56066. }
  56067. }
  56068. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56069. return;
  56070. case 5:
  56071. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  56072. return;
  56073. }
  56074. };
  56075. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  56076. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  56077. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  56078. return OculusTouchController;
  56079. }(BABYLON.WebVRController));
  56080. BABYLON.OculusTouchController = OculusTouchController;
  56081. })(BABYLON || (BABYLON = {}));
  56082. //# sourceMappingURL=babylon.oculusTouchController.js.map
  56083. var BABYLON;
  56084. (function (BABYLON) {
  56085. var ViveController = /** @class */ (function (_super) {
  56086. __extends(ViveController, _super);
  56087. function ViveController(vrGamepad) {
  56088. var _this = _super.call(this, vrGamepad) || this;
  56089. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  56090. return _this;
  56091. }
  56092. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56093. var _this = this;
  56094. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  56095. /*
  56096. Parent Mesh name: ViveWand
  56097. - body
  56098. - r_gripper
  56099. - l_gripper
  56100. - menu_button
  56101. - system_button
  56102. - trackpad
  56103. - trigger
  56104. - LED
  56105. */
  56106. _this._defaultModel = newMeshes[1];
  56107. _this.attachToMesh(_this._defaultModel);
  56108. if (meshLoaded) {
  56109. meshLoaded(_this._defaultModel);
  56110. }
  56111. });
  56112. };
  56113. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  56114. get: function () {
  56115. return this.onMainButtonStateChangedObservable;
  56116. },
  56117. enumerable: true,
  56118. configurable: true
  56119. });
  56120. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  56121. get: function () {
  56122. return this.onMainButtonStateChangedObservable;
  56123. },
  56124. enumerable: true,
  56125. configurable: true
  56126. });
  56127. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  56128. get: function () {
  56129. return this.onSecondaryButtonStateChangedObservable;
  56130. },
  56131. enumerable: true,
  56132. configurable: true
  56133. });
  56134. /**
  56135. * Vive mapping:
  56136. * 0: touchpad
  56137. * 1: trigger
  56138. * 2: left AND right buttons
  56139. * 3: menu button
  56140. */
  56141. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56142. var notifyObject = state; //{ state: state, changes: changes };
  56143. switch (buttonIdx) {
  56144. case 0:
  56145. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  56146. return;
  56147. case 1:// index trigger
  56148. if (this._defaultModel) {
  56149. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  56150. }
  56151. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  56152. return;
  56153. case 2:// left AND right button
  56154. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  56155. return;
  56156. case 3:
  56157. if (this._defaultModel) {
  56158. if (notifyObject.pressed) {
  56159. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  56160. }
  56161. else {
  56162. (this._defaultModel.getChildren()[2]).position.y = 0;
  56163. }
  56164. }
  56165. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  56166. return;
  56167. }
  56168. };
  56169. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  56170. ViveController.MODEL_FILENAME = 'wand.babylon';
  56171. return ViveController;
  56172. }(BABYLON.WebVRController));
  56173. BABYLON.ViveController = ViveController;
  56174. })(BABYLON || (BABYLON = {}));
  56175. //# sourceMappingURL=babylon.viveController.js.map
  56176. var BABYLON;
  56177. (function (BABYLON) {
  56178. var GenericController = /** @class */ (function (_super) {
  56179. __extends(GenericController, _super);
  56180. function GenericController(vrGamepad) {
  56181. return _super.call(this, vrGamepad) || this;
  56182. }
  56183. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  56184. var _this = this;
  56185. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  56186. _this._defaultModel = newMeshes[1];
  56187. _this.attachToMesh(_this._defaultModel);
  56188. if (meshLoaded) {
  56189. meshLoaded(_this._defaultModel);
  56190. }
  56191. });
  56192. };
  56193. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56194. console.log("Button id: " + buttonIdx + "state: ");
  56195. console.dir(state);
  56196. };
  56197. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  56198. GenericController.MODEL_FILENAME = 'generic.babylon';
  56199. return GenericController;
  56200. }(BABYLON.WebVRController));
  56201. BABYLON.GenericController = GenericController;
  56202. })(BABYLON || (BABYLON = {}));
  56203. //# sourceMappingURL=babylon.genericController.js.map
  56204. var BABYLON;
  56205. (function (BABYLON) {
  56206. var LoadedMeshInfo = /** @class */ (function () {
  56207. function LoadedMeshInfo() {
  56208. this.buttonMeshes = {};
  56209. this.axisMeshes = {};
  56210. }
  56211. return LoadedMeshInfo;
  56212. }());
  56213. var WindowsMotionController = /** @class */ (function (_super) {
  56214. __extends(WindowsMotionController, _super);
  56215. function WindowsMotionController(vrGamepad) {
  56216. var _this = _super.call(this, vrGamepad) || this;
  56217. _this._mapping = {
  56218. // Semantic button names
  56219. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  56220. // A mapping of the button name to glTF model node name
  56221. // that should be transformed by button value.
  56222. buttonMeshNames: {
  56223. 'trigger': 'SELECT',
  56224. 'menu': 'MENU',
  56225. 'grip': 'GRASP',
  56226. 'thumbstick': 'THUMBSTICK_PRESS',
  56227. 'trackpad': 'TOUCHPAD_PRESS'
  56228. },
  56229. // This mapping is used to translate from the Motion Controller to Babylon semantics
  56230. buttonObservableNames: {
  56231. 'trigger': 'onTriggerStateChangedObservable',
  56232. 'menu': 'onSecondaryButtonStateChangedObservable',
  56233. 'grip': 'onMainButtonStateChangedObservable',
  56234. 'thumbstick': 'onPadStateChangedObservable',
  56235. 'trackpad': 'onTrackpadChangedObservable'
  56236. },
  56237. // A mapping of the axis name to glTF model node name
  56238. // that should be transformed by axis value.
  56239. // This array mirrors the browserGamepad.axes array, such that
  56240. // the mesh corresponding to axis 0 is in this array index 0.
  56241. axisMeshNames: [
  56242. 'THUMBSTICK_X',
  56243. 'THUMBSTICK_Y',
  56244. 'TOUCHPAD_TOUCH_X',
  56245. 'TOUCHPAD_TOUCH_Y'
  56246. ],
  56247. pointingPoseMeshName: 'POINTING_POSE'
  56248. };
  56249. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  56250. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  56251. _this._loadedMeshInfo = null;
  56252. return _this;
  56253. }
  56254. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  56255. get: function () {
  56256. return this.onTriggerStateChangedObservable;
  56257. },
  56258. enumerable: true,
  56259. configurable: true
  56260. });
  56261. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  56262. get: function () {
  56263. return this.onSecondaryButtonStateChangedObservable;
  56264. },
  56265. enumerable: true,
  56266. configurable: true
  56267. });
  56268. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  56269. get: function () {
  56270. return this.onMainButtonStateChangedObservable;
  56271. },
  56272. enumerable: true,
  56273. configurable: true
  56274. });
  56275. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  56276. get: function () {
  56277. return this.onPadStateChangedObservable;
  56278. },
  56279. enumerable: true,
  56280. configurable: true
  56281. });
  56282. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  56283. get: function () {
  56284. return this.onTrackpadChangedObservable;
  56285. },
  56286. enumerable: true,
  56287. configurable: true
  56288. });
  56289. /**
  56290. * Called once per frame by the engine.
  56291. */
  56292. WindowsMotionController.prototype.update = function () {
  56293. _super.prototype.update.call(this);
  56294. // Only need to animate axes if there is a loaded mesh
  56295. if (this._loadedMeshInfo) {
  56296. if (this.browserGamepad.axes) {
  56297. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  56298. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  56299. }
  56300. }
  56301. }
  56302. };
  56303. /**
  56304. * Called once for each button that changed state since the last frame
  56305. * @param buttonIdx Which button index changed
  56306. * @param state New state of the button
  56307. * @param changes Which properties on the state changed since last frame
  56308. */
  56309. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  56310. var buttonName = this._mapping.buttons[buttonIdx];
  56311. if (!buttonName) {
  56312. return;
  56313. }
  56314. // Only emit events for buttons that we know how to map from index to name
  56315. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  56316. if (observable) {
  56317. observable.notifyObservers(state);
  56318. }
  56319. this.lerpButtonTransform(buttonName, state.value);
  56320. };
  56321. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  56322. // If there is no loaded mesh, there is nothing to transform.
  56323. if (!this._loadedMeshInfo) {
  56324. return;
  56325. }
  56326. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  56327. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56328. return;
  56329. }
  56330. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  56331. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  56332. };
  56333. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  56334. if (!this._loadedMeshInfo) {
  56335. return;
  56336. }
  56337. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  56338. if (!meshInfo) {
  56339. return;
  56340. }
  56341. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  56342. return;
  56343. }
  56344. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  56345. var lerpValue = axisValue * 0.5 + 0.5;
  56346. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  56347. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  56348. };
  56349. /**
  56350. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  56351. * @param scene scene in which to add meshes
  56352. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  56353. */
  56354. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  56355. var _this = this;
  56356. if (forceDefault === void 0) { forceDefault = false; }
  56357. var path;
  56358. var filename;
  56359. // Checking if GLB loader is present
  56360. if (BABYLON.SceneLoader.GetPluginForExtension("glb")) {
  56361. // Determine the device specific folder based on the ID suffix
  56362. var device = 'default';
  56363. if (this.id && !forceDefault) {
  56364. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  56365. device = ((match && match[0]) || device);
  56366. }
  56367. // Hand
  56368. if (this.hand === 'left') {
  56369. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  56370. }
  56371. else {
  56372. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  56373. }
  56374. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  56375. }
  56376. else {
  56377. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  56378. path = BABYLON.GenericController.MODEL_BASE_URL;
  56379. filename = BABYLON.GenericController.MODEL_FILENAME;
  56380. }
  56381. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  56382. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  56383. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  56384. if (!_this._loadedMeshInfo) {
  56385. return;
  56386. }
  56387. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  56388. _this.attachToMesh(_this._defaultModel);
  56389. if (meshLoaded) {
  56390. meshLoaded(_this._defaultModel);
  56391. }
  56392. }, null, function (scene, message) {
  56393. BABYLON.Tools.Log(message);
  56394. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  56395. if (!forceDefault) {
  56396. _this.initControllerMesh(scene, meshLoaded, true);
  56397. }
  56398. });
  56399. };
  56400. /**
  56401. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  56402. * can be transformed by button presses and axes values, based on this._mapping.
  56403. *
  56404. * @param scene scene in which the meshes exist
  56405. * @param meshes list of meshes that make up the controller model to process
  56406. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  56407. */
  56408. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  56409. var loadedMeshInfo = null;
  56410. // Create a new mesh to contain the glTF hierarchy
  56411. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  56412. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  56413. var childMesh = null;
  56414. for (var i = 0; i < meshes.length; i++) {
  56415. var mesh = meshes[i];
  56416. if (!mesh.parent) {
  56417. // Exclude controller meshes from picking results
  56418. mesh.isPickable = false;
  56419. // Handle root node, attach to the new parentMesh
  56420. childMesh = mesh;
  56421. break;
  56422. }
  56423. }
  56424. if (childMesh) {
  56425. childMesh.setParent(parentMesh);
  56426. // Create our mesh info. Note that this method will always return non-null.
  56427. loadedMeshInfo = this.createMeshInfo(parentMesh);
  56428. }
  56429. else {
  56430. BABYLON.Tools.Warn('Could not find root node in model file.');
  56431. }
  56432. return loadedMeshInfo;
  56433. };
  56434. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  56435. var loadedMeshInfo = new LoadedMeshInfo();
  56436. var i;
  56437. loadedMeshInfo.rootNode = rootNode;
  56438. // Reset the caches
  56439. loadedMeshInfo.buttonMeshes = {};
  56440. loadedMeshInfo.axisMeshes = {};
  56441. // Button Meshes
  56442. for (i = 0; i < this._mapping.buttons.length; i++) {
  56443. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  56444. if (!buttonMeshName) {
  56445. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  56446. continue;
  56447. }
  56448. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  56449. if (!buttonMesh) {
  56450. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  56451. continue;
  56452. }
  56453. var buttonMeshInfo = {
  56454. index: i,
  56455. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  56456. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  56457. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  56458. };
  56459. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  56460. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  56461. }
  56462. else {
  56463. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  56464. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  56465. '(VALUE: ' + !!buttonMeshInfo.value +
  56466. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  56467. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  56468. ')');
  56469. }
  56470. }
  56471. // Axis Meshes
  56472. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  56473. var axisMeshName = this._mapping.axisMeshNames[i];
  56474. if (!axisMeshName) {
  56475. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  56476. continue;
  56477. }
  56478. var axisMesh = getChildByName(rootNode, axisMeshName);
  56479. if (!axisMesh) {
  56480. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  56481. continue;
  56482. }
  56483. var axisMeshInfo = {
  56484. index: i,
  56485. value: getImmediateChildByName(axisMesh, 'VALUE'),
  56486. min: getImmediateChildByName(axisMesh, 'MIN'),
  56487. max: getImmediateChildByName(axisMesh, 'MAX')
  56488. };
  56489. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  56490. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  56491. }
  56492. else {
  56493. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  56494. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  56495. '(VALUE: ' + !!axisMeshInfo.value +
  56496. ', MIN: ' + !!axisMeshInfo.min +
  56497. ', MAX:' + !!axisMeshInfo.max +
  56498. ')');
  56499. }
  56500. }
  56501. // Pointing Ray
  56502. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  56503. if (!loadedMeshInfo.pointingPoseNode) {
  56504. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  56505. }
  56506. return loadedMeshInfo;
  56507. // Look through all children recursively. This will return null if no mesh exists with the given name.
  56508. function getChildByName(node, name) {
  56509. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  56510. }
  56511. // Look through only immediate children. This will return null if no mesh exists with the given name.
  56512. function getImmediateChildByName(node, name) {
  56513. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  56514. }
  56515. };
  56516. WindowsMotionController.prototype.getForwardRay = function (length) {
  56517. if (length === void 0) { length = 100; }
  56518. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  56519. return _super.prototype.getForwardRay.call(this, length);
  56520. }
  56521. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  56522. var origin = m.getTranslation();
  56523. var forward = new BABYLON.Vector3(0, 0, -1);
  56524. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  56525. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  56526. return new BABYLON.Ray(origin, direction, length);
  56527. };
  56528. WindowsMotionController.prototype.dispose = function () {
  56529. _super.prototype.dispose.call(this);
  56530. this.onTrackpadChangedObservable.clear();
  56531. };
  56532. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  56533. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  56534. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  56535. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  56536. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  56537. return WindowsMotionController;
  56538. }(BABYLON.WebVRController));
  56539. BABYLON.WindowsMotionController = WindowsMotionController;
  56540. })(BABYLON || (BABYLON = {}));
  56541. //# sourceMappingURL=babylon.windowsMotionController.js.map
  56542. var BABYLON;
  56543. (function (BABYLON) {
  56544. var FollowCamera = /** @class */ (function (_super) {
  56545. __extends(FollowCamera, _super);
  56546. function FollowCamera(name, position, scene, lockedTarget) {
  56547. if (lockedTarget === void 0) { lockedTarget = null; }
  56548. var _this = _super.call(this, name, position, scene) || this;
  56549. _this.radius = 12;
  56550. _this.rotationOffset = 0;
  56551. _this.heightOffset = 4;
  56552. _this.cameraAcceleration = 0.05;
  56553. _this.maxCameraSpeed = 20;
  56554. _this.lockedTarget = lockedTarget;
  56555. return _this;
  56556. }
  56557. FollowCamera.prototype.getRadians = function (degrees) {
  56558. return degrees * Math.PI / 180;
  56559. };
  56560. FollowCamera.prototype.follow = function (cameraTarget) {
  56561. if (!cameraTarget)
  56562. return;
  56563. var yRotation;
  56564. if (cameraTarget.rotationQuaternion) {
  56565. var rotMatrix = new BABYLON.Matrix();
  56566. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  56567. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  56568. }
  56569. else {
  56570. yRotation = cameraTarget.rotation.y;
  56571. }
  56572. var radians = this.getRadians(this.rotationOffset) + yRotation;
  56573. var targetPosition = cameraTarget.getAbsolutePosition();
  56574. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  56575. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  56576. var dx = targetX - this.position.x;
  56577. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  56578. var dz = (targetZ) - this.position.z;
  56579. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  56580. var vy = dy * this.cameraAcceleration;
  56581. var vz = dz * this.cameraAcceleration * 2;
  56582. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  56583. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56584. }
  56585. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  56586. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56587. }
  56588. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  56589. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  56590. }
  56591. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  56592. this.setTarget(targetPosition);
  56593. };
  56594. FollowCamera.prototype._checkInputs = function () {
  56595. _super.prototype._checkInputs.call(this);
  56596. if (this.lockedTarget) {
  56597. this.follow(this.lockedTarget);
  56598. }
  56599. };
  56600. FollowCamera.prototype.getClassName = function () {
  56601. return "FollowCamera";
  56602. };
  56603. __decorate([
  56604. BABYLON.serialize()
  56605. ], FollowCamera.prototype, "radius", void 0);
  56606. __decorate([
  56607. BABYLON.serialize()
  56608. ], FollowCamera.prototype, "rotationOffset", void 0);
  56609. __decorate([
  56610. BABYLON.serialize()
  56611. ], FollowCamera.prototype, "heightOffset", void 0);
  56612. __decorate([
  56613. BABYLON.serialize()
  56614. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  56615. __decorate([
  56616. BABYLON.serialize()
  56617. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  56618. __decorate([
  56619. BABYLON.serializeAsMeshReference("lockedTargetId")
  56620. ], FollowCamera.prototype, "lockedTarget", void 0);
  56621. return FollowCamera;
  56622. }(BABYLON.TargetCamera));
  56623. BABYLON.FollowCamera = FollowCamera;
  56624. var ArcFollowCamera = /** @class */ (function (_super) {
  56625. __extends(ArcFollowCamera, _super);
  56626. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  56627. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  56628. _this.alpha = alpha;
  56629. _this.beta = beta;
  56630. _this.radius = radius;
  56631. _this.target = target;
  56632. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  56633. _this.follow();
  56634. return _this;
  56635. }
  56636. ArcFollowCamera.prototype.follow = function () {
  56637. if (!this.target) {
  56638. return;
  56639. }
  56640. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  56641. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  56642. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  56643. var targetPosition = this.target.getAbsolutePosition();
  56644. this.position = targetPosition.add(this._cartesianCoordinates);
  56645. this.setTarget(targetPosition);
  56646. };
  56647. ArcFollowCamera.prototype._checkInputs = function () {
  56648. _super.prototype._checkInputs.call(this);
  56649. this.follow();
  56650. };
  56651. ArcFollowCamera.prototype.getClassName = function () {
  56652. return "ArcFollowCamera";
  56653. };
  56654. return ArcFollowCamera;
  56655. }(BABYLON.TargetCamera));
  56656. BABYLON.ArcFollowCamera = ArcFollowCamera;
  56657. })(BABYLON || (BABYLON = {}));
  56658. //# sourceMappingURL=babylon.followCamera.js.map
  56659. var BABYLON;
  56660. (function (BABYLON) {
  56661. // We're mainly based on the logic defined into the FreeCamera code
  56662. var UniversalCamera = /** @class */ (function (_super) {
  56663. __extends(UniversalCamera, _super);
  56664. //-- end properties for backward compatibility for inputs
  56665. function UniversalCamera(name, position, scene) {
  56666. var _this = _super.call(this, name, position, scene) || this;
  56667. _this.inputs.addGamepad();
  56668. return _this;
  56669. }
  56670. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  56671. //-- Begin properties for backward compatibility for inputs
  56672. get: function () {
  56673. var gamepad = this.inputs.attached["gamepad"];
  56674. if (gamepad)
  56675. return gamepad.gamepadAngularSensibility;
  56676. return 0;
  56677. },
  56678. set: function (value) {
  56679. var gamepad = this.inputs.attached["gamepad"];
  56680. if (gamepad)
  56681. gamepad.gamepadAngularSensibility = value;
  56682. },
  56683. enumerable: true,
  56684. configurable: true
  56685. });
  56686. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  56687. get: function () {
  56688. var gamepad = this.inputs.attached["gamepad"];
  56689. if (gamepad)
  56690. return gamepad.gamepadMoveSensibility;
  56691. return 0;
  56692. },
  56693. set: function (value) {
  56694. var gamepad = this.inputs.attached["gamepad"];
  56695. if (gamepad)
  56696. gamepad.gamepadMoveSensibility = value;
  56697. },
  56698. enumerable: true,
  56699. configurable: true
  56700. });
  56701. UniversalCamera.prototype.getClassName = function () {
  56702. return "UniversalCamera";
  56703. };
  56704. return UniversalCamera;
  56705. }(BABYLON.TouchCamera));
  56706. BABYLON.UniversalCamera = UniversalCamera;
  56707. })(BABYLON || (BABYLON = {}));
  56708. //# sourceMappingURL=babylon.universalCamera.js.map
  56709. var BABYLON;
  56710. (function (BABYLON) {
  56711. // We're mainly based on the logic defined into the FreeCamera code
  56712. var GamepadCamera = /** @class */ (function (_super) {
  56713. __extends(GamepadCamera, _super);
  56714. //-- end properties for backward compatibility for inputs
  56715. function GamepadCamera(name, position, scene) {
  56716. return _super.call(this, name, position, scene) || this;
  56717. }
  56718. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  56719. //-- Begin properties for backward compatibility for inputs
  56720. get: function () {
  56721. var gamepad = this.inputs.attached["gamepad"];
  56722. if (gamepad)
  56723. return gamepad.gamepadAngularSensibility;
  56724. return 0;
  56725. },
  56726. set: function (value) {
  56727. var gamepad = this.inputs.attached["gamepad"];
  56728. if (gamepad)
  56729. gamepad.gamepadAngularSensibility = value;
  56730. },
  56731. enumerable: true,
  56732. configurable: true
  56733. });
  56734. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  56735. get: function () {
  56736. var gamepad = this.inputs.attached["gamepad"];
  56737. if (gamepad)
  56738. return gamepad.gamepadMoveSensibility;
  56739. return 0;
  56740. },
  56741. set: function (value) {
  56742. var gamepad = this.inputs.attached["gamepad"];
  56743. if (gamepad)
  56744. gamepad.gamepadMoveSensibility = value;
  56745. },
  56746. enumerable: true,
  56747. configurable: true
  56748. });
  56749. GamepadCamera.prototype.getClassName = function () {
  56750. return "GamepadCamera";
  56751. };
  56752. return GamepadCamera;
  56753. }(BABYLON.UniversalCamera));
  56754. BABYLON.GamepadCamera = GamepadCamera;
  56755. })(BABYLON || (BABYLON = {}));
  56756. //# sourceMappingURL=babylon.gamepadCamera.js.map
  56757. var BABYLON;
  56758. (function (BABYLON) {
  56759. var PostProcessRenderPipelineManager = /** @class */ (function () {
  56760. function PostProcessRenderPipelineManager() {
  56761. this._renderPipelines = {};
  56762. }
  56763. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  56764. this._renderPipelines[renderPipeline._name] = renderPipeline;
  56765. };
  56766. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  56767. if (unique === void 0) { unique = false; }
  56768. var renderPipeline = this._renderPipelines[renderPipelineName];
  56769. if (!renderPipeline) {
  56770. return;
  56771. }
  56772. renderPipeline._attachCameras(cameras, unique);
  56773. };
  56774. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  56775. var renderPipeline = this._renderPipelines[renderPipelineName];
  56776. if (!renderPipeline) {
  56777. return;
  56778. }
  56779. renderPipeline._detachCameras(cameras);
  56780. };
  56781. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56782. var renderPipeline = this._renderPipelines[renderPipelineName];
  56783. if (!renderPipeline) {
  56784. return;
  56785. }
  56786. renderPipeline._enableEffect(renderEffectName, cameras);
  56787. };
  56788. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  56789. var renderPipeline = this._renderPipelines[renderPipelineName];
  56790. if (!renderPipeline) {
  56791. return;
  56792. }
  56793. renderPipeline._disableEffect(renderEffectName, cameras);
  56794. };
  56795. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  56796. var renderPipeline = this._renderPipelines[renderPipelineName];
  56797. if (!renderPipeline) {
  56798. return;
  56799. }
  56800. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  56801. };
  56802. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  56803. var renderPipeline = this._renderPipelines[renderPipelineName];
  56804. if (!renderPipeline) {
  56805. return;
  56806. }
  56807. renderPipeline._disableDisplayOnlyPass(cameras);
  56808. };
  56809. PostProcessRenderPipelineManager.prototype.update = function () {
  56810. for (var renderPipelineName in this._renderPipelines) {
  56811. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56812. var pipeline = this._renderPipelines[renderPipelineName];
  56813. if (!pipeline.isSupported) {
  56814. pipeline.dispose();
  56815. delete this._renderPipelines[renderPipelineName];
  56816. }
  56817. else {
  56818. pipeline._update();
  56819. }
  56820. }
  56821. }
  56822. };
  56823. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  56824. for (var renderPipelineName in this._renderPipelines) {
  56825. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56826. var pipeline = this._renderPipelines[renderPipelineName];
  56827. pipeline._rebuild();
  56828. }
  56829. }
  56830. };
  56831. PostProcessRenderPipelineManager.prototype.dispose = function () {
  56832. for (var renderPipelineName in this._renderPipelines) {
  56833. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  56834. var pipeline = this._renderPipelines[renderPipelineName];
  56835. pipeline.dispose();
  56836. }
  56837. }
  56838. };
  56839. return PostProcessRenderPipelineManager;
  56840. }());
  56841. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  56842. })(BABYLON || (BABYLON = {}));
  56843. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  56844. var BABYLON;
  56845. (function (BABYLON) {
  56846. var PostProcessRenderPass = /** @class */ (function () {
  56847. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  56848. this._refCount = 0;
  56849. this._name = name;
  56850. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  56851. this.setRenderList(renderList);
  56852. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  56853. this._renderTexture.onAfterRenderObservable.add(afterRender);
  56854. this._scene = scene;
  56855. this._renderList = renderList;
  56856. }
  56857. // private
  56858. PostProcessRenderPass.prototype._incRefCount = function () {
  56859. if (this._refCount === 0) {
  56860. this._scene.customRenderTargets.push(this._renderTexture);
  56861. }
  56862. return ++this._refCount;
  56863. };
  56864. PostProcessRenderPass.prototype._decRefCount = function () {
  56865. this._refCount--;
  56866. if (this._refCount <= 0) {
  56867. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  56868. }
  56869. return this._refCount;
  56870. };
  56871. PostProcessRenderPass.prototype._update = function () {
  56872. this.setRenderList(this._renderList);
  56873. };
  56874. // public
  56875. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  56876. this._renderTexture.renderList = renderList;
  56877. };
  56878. PostProcessRenderPass.prototype.getRenderTexture = function () {
  56879. return this._renderTexture;
  56880. };
  56881. return PostProcessRenderPass;
  56882. }());
  56883. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  56884. })(BABYLON || (BABYLON = {}));
  56885. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  56886. var BABYLON;
  56887. (function (BABYLON) {
  56888. var PostProcessRenderEffect = /** @class */ (function () {
  56889. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  56890. this._engine = engine;
  56891. this._name = name;
  56892. this._singleInstance = singleInstance || true;
  56893. this._getPostProcess = getPostProcess;
  56894. this._cameras = {};
  56895. this._indicesForCamera = {};
  56896. this._postProcesses = {};
  56897. this._renderPasses = {};
  56898. this._renderEffectAsPasses = {};
  56899. }
  56900. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  56901. get: function () {
  56902. for (var index in this._postProcesses) {
  56903. if (!this._postProcesses[index].isSupported) {
  56904. return false;
  56905. }
  56906. }
  56907. return true;
  56908. },
  56909. enumerable: true,
  56910. configurable: true
  56911. });
  56912. PostProcessRenderEffect.prototype._update = function () {
  56913. for (var renderPassName in this._renderPasses) {
  56914. this._renderPasses[renderPassName]._update();
  56915. }
  56916. };
  56917. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  56918. this._renderPasses[renderPass._name] = renderPass;
  56919. this._linkParameters();
  56920. };
  56921. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  56922. delete this._renderPasses[renderPass._name];
  56923. this._linkParameters();
  56924. };
  56925. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  56926. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  56927. this._linkParameters();
  56928. };
  56929. PostProcessRenderEffect.prototype.getPass = function (passName) {
  56930. for (var renderPassName in this._renderPasses) {
  56931. if (renderPassName === passName) {
  56932. return this._renderPasses[passName];
  56933. }
  56934. }
  56935. return null;
  56936. };
  56937. PostProcessRenderEffect.prototype.emptyPasses = function () {
  56938. this._renderPasses = {};
  56939. this._linkParameters();
  56940. };
  56941. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  56942. var cameraKey;
  56943. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56944. if (!cams) {
  56945. return;
  56946. }
  56947. for (var i = 0; i < cams.length; i++) {
  56948. var camera = cams[i];
  56949. var cameraName = camera.name;
  56950. if (this._singleInstance) {
  56951. cameraKey = 0;
  56952. }
  56953. else {
  56954. cameraKey = cameraName;
  56955. }
  56956. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  56957. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  56958. if (!this._indicesForCamera[cameraName]) {
  56959. this._indicesForCamera[cameraName] = [];
  56960. }
  56961. this._indicesForCamera[cameraName].push(index);
  56962. if (!this._cameras[cameraName]) {
  56963. this._cameras[cameraName] = camera;
  56964. }
  56965. for (var passName in this._renderPasses) {
  56966. this._renderPasses[passName]._incRefCount();
  56967. }
  56968. }
  56969. this._linkParameters();
  56970. };
  56971. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  56972. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56973. if (!cams) {
  56974. return;
  56975. }
  56976. for (var i = 0; i < cams.length; i++) {
  56977. var camera = cams[i];
  56978. var cameraName = camera.name;
  56979. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  56980. if (this._cameras[cameraName]) {
  56981. //this._indicesForCamera.splice(index, 1);
  56982. this._cameras[cameraName] = null;
  56983. }
  56984. for (var passName in this._renderPasses) {
  56985. this._renderPasses[passName]._decRefCount();
  56986. }
  56987. }
  56988. };
  56989. PostProcessRenderEffect.prototype._enable = function (cameras) {
  56990. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  56991. if (!cams) {
  56992. return;
  56993. }
  56994. for (var i = 0; i < cams.length; i++) {
  56995. var camera = cams[i];
  56996. var cameraName = camera.name;
  56997. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  56998. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  56999. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  57000. }
  57001. }
  57002. for (var passName in this._renderPasses) {
  57003. this._renderPasses[passName]._incRefCount();
  57004. }
  57005. }
  57006. };
  57007. PostProcessRenderEffect.prototype._disable = function (cameras) {
  57008. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57009. if (!cams) {
  57010. return;
  57011. }
  57012. for (var i = 0; i < cams.length; i++) {
  57013. var camera = cams[i];
  57014. var cameraName = camera.Name;
  57015. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  57016. for (var passName in this._renderPasses) {
  57017. this._renderPasses[passName]._decRefCount();
  57018. }
  57019. }
  57020. };
  57021. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  57022. if (this._singleInstance) {
  57023. return this._postProcesses[0];
  57024. }
  57025. else {
  57026. if (!camera) {
  57027. return null;
  57028. }
  57029. return this._postProcesses[camera.name];
  57030. }
  57031. };
  57032. PostProcessRenderEffect.prototype._linkParameters = function () {
  57033. var _this = this;
  57034. for (var index in this._postProcesses) {
  57035. if (this.applyParameters) {
  57036. this.applyParameters(this._postProcesses[index]);
  57037. }
  57038. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  57039. _this._linkTextures(effect);
  57040. });
  57041. }
  57042. };
  57043. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  57044. for (var renderPassName in this._renderPasses) {
  57045. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  57046. }
  57047. for (var renderEffectName in this._renderEffectAsPasses) {
  57048. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  57049. }
  57050. };
  57051. return PostProcessRenderEffect;
  57052. }());
  57053. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  57054. })(BABYLON || (BABYLON = {}));
  57055. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  57056. var BABYLON;
  57057. (function (BABYLON) {
  57058. var PostProcessRenderPipeline = /** @class */ (function () {
  57059. function PostProcessRenderPipeline(engine, name) {
  57060. this._engine = engine;
  57061. this._name = name;
  57062. this._renderEffects = {};
  57063. this._renderEffectsForIsolatedPass = new Array();
  57064. this._cameras = [];
  57065. }
  57066. PostProcessRenderPipeline.prototype.getClassName = function () {
  57067. return "PostProcessRenderPipeline";
  57068. };
  57069. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  57070. get: function () {
  57071. for (var renderEffectName in this._renderEffects) {
  57072. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57073. if (!this._renderEffects[renderEffectName].isSupported) {
  57074. return false;
  57075. }
  57076. }
  57077. }
  57078. return true;
  57079. },
  57080. enumerable: true,
  57081. configurable: true
  57082. });
  57083. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  57084. this._renderEffects[renderEffect._name] = renderEffect;
  57085. };
  57086. // private
  57087. PostProcessRenderPipeline.prototype._rebuild = function () {
  57088. };
  57089. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  57090. var renderEffects = this._renderEffects[renderEffectName];
  57091. if (!renderEffects) {
  57092. return;
  57093. }
  57094. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57095. };
  57096. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  57097. var renderEffects = this._renderEffects[renderEffectName];
  57098. if (!renderEffects) {
  57099. return;
  57100. }
  57101. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  57102. };
  57103. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  57104. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57105. if (!cams) {
  57106. return;
  57107. }
  57108. var indicesToDelete = [];
  57109. var i;
  57110. for (i = 0; i < cams.length; i++) {
  57111. var camera = cams[i];
  57112. var cameraName = camera.name;
  57113. if (this._cameras.indexOf(camera) === -1) {
  57114. this._cameras[cameraName] = camera;
  57115. }
  57116. else if (unique) {
  57117. indicesToDelete.push(i);
  57118. }
  57119. }
  57120. for (i = 0; i < indicesToDelete.length; i++) {
  57121. cameras.splice(indicesToDelete[i], 1);
  57122. }
  57123. for (var renderEffectName in this._renderEffects) {
  57124. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57125. this._renderEffects[renderEffectName]._attachCameras(cams);
  57126. }
  57127. }
  57128. };
  57129. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  57130. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57131. if (!cams) {
  57132. return;
  57133. }
  57134. for (var renderEffectName in this._renderEffects) {
  57135. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57136. this._renderEffects[renderEffectName]._detachCameras(cams);
  57137. }
  57138. }
  57139. for (var i = 0; i < cams.length; i++) {
  57140. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  57141. }
  57142. };
  57143. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  57144. var _this = this;
  57145. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57146. if (!cams) {
  57147. return;
  57148. }
  57149. var pass = null;
  57150. var renderEffectName;
  57151. for (renderEffectName in this._renderEffects) {
  57152. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57153. pass = this._renderEffects[renderEffectName].getPass(passName);
  57154. if (pass != null) {
  57155. break;
  57156. }
  57157. }
  57158. }
  57159. if (pass === null) {
  57160. return;
  57161. }
  57162. for (renderEffectName in this._renderEffects) {
  57163. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57164. this._renderEffects[renderEffectName]._disable(cams);
  57165. }
  57166. }
  57167. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  57168. for (var i = 0; i < cams.length; i++) {
  57169. var camera = cams[i];
  57170. var cameraName = camera.name;
  57171. 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); });
  57172. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  57173. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  57174. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  57175. }
  57176. };
  57177. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  57178. var _this = this;
  57179. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  57180. if (!cams) {
  57181. return;
  57182. }
  57183. for (var i = 0; i < cams.length; i++) {
  57184. var camera = cams[i];
  57185. var cameraName = camera.name;
  57186. 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); });
  57187. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  57188. }
  57189. for (var renderEffectName in this._renderEffects) {
  57190. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57191. this._renderEffects[renderEffectName]._enable(cams);
  57192. }
  57193. }
  57194. };
  57195. PostProcessRenderPipeline.prototype._update = function () {
  57196. for (var renderEffectName in this._renderEffects) {
  57197. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  57198. this._renderEffects[renderEffectName]._update();
  57199. }
  57200. }
  57201. for (var i = 0; i < this._cameras.length; i++) {
  57202. var cameraName = this._cameras[i].name;
  57203. if (this._renderEffectsForIsolatedPass[cameraName]) {
  57204. this._renderEffectsForIsolatedPass[cameraName]._update();
  57205. }
  57206. }
  57207. };
  57208. PostProcessRenderPipeline.prototype._reset = function () {
  57209. this._renderEffects = {};
  57210. this._renderEffectsForIsolatedPass = new Array();
  57211. };
  57212. PostProcessRenderPipeline.prototype.dispose = function () {
  57213. // Must be implemented by children
  57214. };
  57215. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  57216. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  57217. __decorate([
  57218. BABYLON.serialize()
  57219. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  57220. return PostProcessRenderPipeline;
  57221. }());
  57222. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  57223. })(BABYLON || (BABYLON = {}));
  57224. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  57225. var BABYLON;
  57226. (function (BABYLON) {
  57227. var DepthRenderer = /** @class */ (function () {
  57228. function DepthRenderer(scene, type) {
  57229. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  57230. var _this = this;
  57231. this._scene = scene;
  57232. var engine = scene.getEngine();
  57233. // Render target
  57234. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  57235. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57236. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57237. this._depthMap.refreshRate = 1;
  57238. this._depthMap.renderParticles = false;
  57239. this._depthMap.renderList = null;
  57240. // set default depth value to 1.0 (far away)
  57241. this._depthMap.onClearObservable.add(function (engine) {
  57242. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  57243. });
  57244. // Custom render function
  57245. var renderSubMesh = function (subMesh) {
  57246. var mesh = subMesh.getRenderingMesh();
  57247. var scene = _this._scene;
  57248. var engine = scene.getEngine();
  57249. var material = subMesh.getMaterial();
  57250. if (!material) {
  57251. return;
  57252. }
  57253. // Culling
  57254. engine.setState(material.backFaceCulling);
  57255. // Managing instances
  57256. var batch = mesh._getInstancesRenderList(subMesh._id);
  57257. if (batch.mustReturn) {
  57258. return;
  57259. }
  57260. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  57261. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  57262. engine.enableEffect(_this._effect);
  57263. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  57264. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  57265. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  57266. // Alpha test
  57267. if (material && material.needAlphaTesting()) {
  57268. var alphaTexture = material.getAlphaTestTexture();
  57269. if (alphaTexture) {
  57270. _this._effect.setTexture("diffuseSampler", alphaTexture);
  57271. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  57272. }
  57273. }
  57274. // Bones
  57275. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  57276. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  57277. }
  57278. // Draw
  57279. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  57280. }
  57281. };
  57282. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  57283. var index;
  57284. if (depthOnlySubMeshes.length) {
  57285. engine.setColorWrite(false);
  57286. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  57287. renderSubMesh(depthOnlySubMeshes.data[index]);
  57288. }
  57289. engine.setColorWrite(true);
  57290. }
  57291. for (index = 0; index < opaqueSubMeshes.length; index++) {
  57292. renderSubMesh(opaqueSubMeshes.data[index]);
  57293. }
  57294. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  57295. renderSubMesh(alphaTestSubMeshes.data[index]);
  57296. }
  57297. };
  57298. }
  57299. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  57300. var material = subMesh.getMaterial();
  57301. if (material.disableDepthWrite) {
  57302. return false;
  57303. }
  57304. var defines = [];
  57305. var attribs = [BABYLON.VertexBuffer.PositionKind];
  57306. var mesh = subMesh.getMesh();
  57307. // Alpha test
  57308. if (material && material.needAlphaTesting()) {
  57309. defines.push("#define ALPHATEST");
  57310. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57311. attribs.push(BABYLON.VertexBuffer.UVKind);
  57312. defines.push("#define UV1");
  57313. }
  57314. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  57315. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  57316. defines.push("#define UV2");
  57317. }
  57318. }
  57319. // Bones
  57320. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  57321. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  57322. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  57323. if (mesh.numBoneInfluencers > 4) {
  57324. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  57325. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  57326. }
  57327. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  57328. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  57329. }
  57330. else {
  57331. defines.push("#define NUM_BONE_INFLUENCERS 0");
  57332. }
  57333. // Instances
  57334. if (useInstances) {
  57335. defines.push("#define INSTANCES");
  57336. attribs.push("world0");
  57337. attribs.push("world1");
  57338. attribs.push("world2");
  57339. attribs.push("world3");
  57340. }
  57341. // Get correct effect
  57342. var join = defines.join("\n");
  57343. if (this._cachedDefines !== join) {
  57344. this._cachedDefines = join;
  57345. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  57346. }
  57347. return this._effect.isReady();
  57348. };
  57349. DepthRenderer.prototype.getDepthMap = function () {
  57350. return this._depthMap;
  57351. };
  57352. // Methods
  57353. DepthRenderer.prototype.dispose = function () {
  57354. this._depthMap.dispose();
  57355. };
  57356. return DepthRenderer;
  57357. }());
  57358. BABYLON.DepthRenderer = DepthRenderer;
  57359. })(BABYLON || (BABYLON = {}));
  57360. //# sourceMappingURL=babylon.depthRenderer.js.map
  57361. var BABYLON;
  57362. (function (BABYLON) {
  57363. var SSAORenderingPipeline = /** @class */ (function (_super) {
  57364. __extends(SSAORenderingPipeline, _super);
  57365. /**
  57366. * @constructor
  57367. * @param {string} name - The rendering pipeline name
  57368. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57369. * @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 }
  57370. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57371. */
  57372. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  57373. var _this = _super.call(this, scene.getEngine(), name) || this;
  57374. // Members
  57375. /**
  57376. * The PassPostProcess id in the pipeline that contains the original scene color
  57377. * @type {string}
  57378. */
  57379. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57380. /**
  57381. * The SSAO PostProcess id in the pipeline
  57382. * @type {string}
  57383. */
  57384. _this.SSAORenderEffect = "SSAORenderEffect";
  57385. /**
  57386. * The horizontal blur PostProcess id in the pipeline
  57387. * @type {string}
  57388. */
  57389. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57390. /**
  57391. * The vertical blur PostProcess id in the pipeline
  57392. * @type {string}
  57393. */
  57394. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57395. /**
  57396. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57397. * @type {string}
  57398. */
  57399. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57400. /**
  57401. * The output strength of the SSAO post-process. Default value is 1.0.
  57402. * @type {number}
  57403. */
  57404. _this.totalStrength = 1.0;
  57405. /**
  57406. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  57407. * @type {number}
  57408. */
  57409. _this.radius = 0.0001;
  57410. /**
  57411. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  57412. * Must not be equal to fallOff and superior to fallOff.
  57413. * Default value is 0.975
  57414. * @type {number}
  57415. */
  57416. _this.area = 0.0075;
  57417. /**
  57418. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  57419. * Must not be equal to area and inferior to area.
  57420. * Default value is 0.0
  57421. * @type {number}
  57422. */
  57423. _this.fallOff = 0.000001;
  57424. /**
  57425. * The base color of the SSAO post-process
  57426. * The final result is "base + ssao" between [0, 1]
  57427. * @type {number}
  57428. */
  57429. _this.base = 0.5;
  57430. _this._firstUpdate = true;
  57431. _this._scene = scene;
  57432. // Set up assets
  57433. _this._createRandomTexture();
  57434. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57435. var ssaoRatio = ratio.ssaoRatio || ratio;
  57436. var combineRatio = ratio.combineRatio || ratio;
  57437. _this._ratio = {
  57438. ssaoRatio: ssaoRatio,
  57439. combineRatio: combineRatio
  57440. };
  57441. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57442. _this._createSSAOPostProcess(ssaoRatio);
  57443. _this._createBlurPostProcess(ssaoRatio);
  57444. _this._createSSAOCombinePostProcess(combineRatio);
  57445. // Set up pipeline
  57446. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57447. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57448. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57449. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57450. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57451. // Finish
  57452. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57453. if (cameras)
  57454. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57455. return _this;
  57456. }
  57457. // Public Methods
  57458. /**
  57459. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57460. */
  57461. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  57462. if (disableDepthRender === void 0) { disableDepthRender = false; }
  57463. for (var i = 0; i < this._scene.cameras.length; i++) {
  57464. var camera = this._scene.cameras[i];
  57465. this._originalColorPostProcess.dispose(camera);
  57466. this._ssaoPostProcess.dispose(camera);
  57467. this._blurHPostProcess.dispose(camera);
  57468. this._blurVPostProcess.dispose(camera);
  57469. this._ssaoCombinePostProcess.dispose(camera);
  57470. }
  57471. this._randomTexture.dispose();
  57472. if (disableDepthRender)
  57473. this._scene.disableDepthRenderer();
  57474. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57475. _super.prototype.dispose.call(this);
  57476. };
  57477. // Private Methods
  57478. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  57479. var _this = this;
  57480. /*
  57481. var samplerOffsets = [
  57482. -8.0, -6.0, -4.0, -2.0,
  57483. 0.0,
  57484. 2.0, 4.0, 6.0, 8.0
  57485. ];
  57486. */
  57487. var samplerOffsets = new Array();
  57488. for (var i = -8; i < 8; i++) {
  57489. samplerOffsets.push(i * 2);
  57490. }
  57491. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  57492. this._blurHPostProcess.onApply = function (effect) {
  57493. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57494. effect.setTexture("depthSampler", _this._depthTexture);
  57495. if (_this._firstUpdate) {
  57496. effect.setArray("samplerOffsets", samplerOffsets);
  57497. }
  57498. };
  57499. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  57500. this._blurVPostProcess.onApply = function (effect) {
  57501. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57502. effect.setTexture("depthSampler", _this._depthTexture);
  57503. if (_this._firstUpdate) {
  57504. effect.setArray("samplerOffsets", samplerOffsets);
  57505. _this._firstUpdate = false;
  57506. }
  57507. };
  57508. };
  57509. SSAORenderingPipeline.prototype._rebuild = function () {
  57510. this._firstUpdate = true;
  57511. _super.prototype._rebuild.call(this);
  57512. };
  57513. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57514. var _this = this;
  57515. var numSamples = 16;
  57516. var sampleSphere = [
  57517. 0.5381, 0.1856, -0.4319,
  57518. 0.1379, 0.2486, 0.4430,
  57519. 0.3371, 0.5679, -0.0057,
  57520. -0.6999, -0.0451, -0.0019,
  57521. 0.0689, -0.1598, -0.8547,
  57522. 0.0560, 0.0069, -0.1843,
  57523. -0.0146, 0.1402, 0.0762,
  57524. 0.0100, -0.1924, -0.0344,
  57525. -0.3577, -0.5301, -0.4358,
  57526. -0.3169, 0.1063, 0.0158,
  57527. 0.0103, -0.5869, 0.0046,
  57528. -0.0897, -0.4940, 0.3287,
  57529. 0.7119, -0.0154, -0.0918,
  57530. -0.0533, 0.0596, -0.5411,
  57531. 0.0352, -0.0631, 0.5460,
  57532. -0.4776, 0.2847, -0.0271
  57533. ];
  57534. var samplesFactor = 1.0 / numSamples;
  57535. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  57536. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57537. "area", "fallOff", "base", "range", "viewport"
  57538. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57539. this._ssaoPostProcess.onApply = function (effect) {
  57540. if (_this._firstUpdate) {
  57541. effect.setArray3("sampleSphere", sampleSphere);
  57542. effect.setFloat("samplesFactor", samplesFactor);
  57543. effect.setFloat("randTextureTiles", 4.0);
  57544. }
  57545. effect.setFloat("totalStrength", _this.totalStrength);
  57546. effect.setFloat("radius", _this.radius);
  57547. effect.setFloat("area", _this.area);
  57548. effect.setFloat("fallOff", _this.fallOff);
  57549. effect.setFloat("base", _this.base);
  57550. effect.setTexture("textureSampler", _this._depthTexture);
  57551. effect.setTexture("randomSampler", _this._randomTexture);
  57552. };
  57553. };
  57554. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57555. var _this = this;
  57556. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57557. this._ssaoCombinePostProcess.onApply = function (effect) {
  57558. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57559. };
  57560. };
  57561. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  57562. var size = 512;
  57563. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57564. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57565. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57566. var context = this._randomTexture.getContext();
  57567. var rand = function (min, max) {
  57568. return Math.random() * (max - min) + min;
  57569. };
  57570. var randVector = BABYLON.Vector3.Zero();
  57571. for (var x = 0; x < size; x++) {
  57572. for (var y = 0; y < size; y++) {
  57573. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  57574. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  57575. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  57576. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57577. context.fillRect(x, y, 1, 1);
  57578. }
  57579. }
  57580. this._randomTexture.update(false);
  57581. };
  57582. __decorate([
  57583. BABYLON.serialize()
  57584. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  57585. __decorate([
  57586. BABYLON.serialize()
  57587. ], SSAORenderingPipeline.prototype, "radius", void 0);
  57588. __decorate([
  57589. BABYLON.serialize()
  57590. ], SSAORenderingPipeline.prototype, "area", void 0);
  57591. __decorate([
  57592. BABYLON.serialize()
  57593. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  57594. __decorate([
  57595. BABYLON.serialize()
  57596. ], SSAORenderingPipeline.prototype, "base", void 0);
  57597. __decorate([
  57598. BABYLON.serialize()
  57599. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  57600. return SSAORenderingPipeline;
  57601. }(BABYLON.PostProcessRenderPipeline));
  57602. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  57603. })(BABYLON || (BABYLON = {}));
  57604. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  57605. var BABYLON;
  57606. (function (BABYLON) {
  57607. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  57608. __extends(SSAO2RenderingPipeline, _super);
  57609. /**
  57610. * @constructor
  57611. * @param {string} name - The rendering pipeline name
  57612. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57613. * @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 }
  57614. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57615. */
  57616. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  57617. var _this = _super.call(this, scene.getEngine(), name) || this;
  57618. // Members
  57619. /**
  57620. * The PassPostProcess id in the pipeline that contains the original scene color
  57621. * @type {string}
  57622. */
  57623. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  57624. /**
  57625. * The SSAO PostProcess id in the pipeline
  57626. * @type {string}
  57627. */
  57628. _this.SSAORenderEffect = "SSAORenderEffect";
  57629. /**
  57630. * The horizontal blur PostProcess id in the pipeline
  57631. * @type {string}
  57632. */
  57633. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  57634. /**
  57635. * The vertical blur PostProcess id in the pipeline
  57636. * @type {string}
  57637. */
  57638. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  57639. /**
  57640. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  57641. * @type {string}
  57642. */
  57643. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  57644. /**
  57645. * The output strength of the SSAO post-process. Default value is 1.0.
  57646. * @type {number}
  57647. */
  57648. _this.totalStrength = 1.0;
  57649. /**
  57650. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  57651. * @type {number}
  57652. */
  57653. _this.maxZ = 100.0;
  57654. /**
  57655. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  57656. * @type {number}
  57657. */
  57658. _this.minZAspect = 0.2;
  57659. /**
  57660. * Number of samples used for the SSAO calculations. Default value is 8
  57661. * @type {number}
  57662. */
  57663. _this._samples = 8;
  57664. /**
  57665. * Are we using bilateral blur ?
  57666. * @type {boolean}
  57667. */
  57668. _this._expensiveBlur = true;
  57669. /**
  57670. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  57671. * @type {number}
  57672. */
  57673. _this.radius = 2.0;
  57674. /**
  57675. * The base color of the SSAO post-process
  57676. * The final result is "base + ssao" between [0, 1]
  57677. * @type {number}
  57678. */
  57679. _this.base = 0.1;
  57680. _this._firstUpdate = true;
  57681. _this._scene = scene;
  57682. if (!_this.isSupported) {
  57683. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  57684. return _this;
  57685. }
  57686. var ssaoRatio = ratio.ssaoRatio || ratio;
  57687. var blurRatio = ratio.blurRatio || ratio;
  57688. _this._ratio = {
  57689. ssaoRatio: ssaoRatio,
  57690. blurRatio: blurRatio
  57691. };
  57692. // Set up assets
  57693. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  57694. _this._createRandomTexture();
  57695. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  57696. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  57697. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  57698. _this._createSSAOPostProcess(1.0);
  57699. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  57700. _this._createSSAOCombinePostProcess(blurRatio);
  57701. // Set up pipeline
  57702. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  57703. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  57704. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  57705. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  57706. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  57707. // Finish
  57708. scene.postProcessRenderPipelineManager.addPipeline(_this);
  57709. if (cameras)
  57710. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  57711. return _this;
  57712. }
  57713. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  57714. get: function () {
  57715. return this._samples;
  57716. },
  57717. set: function (n) {
  57718. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  57719. this._samples = n;
  57720. this._sampleSphere = this._generateHemisphere();
  57721. this._firstUpdate = true;
  57722. },
  57723. enumerable: true,
  57724. configurable: true
  57725. });
  57726. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  57727. get: function () {
  57728. return this._expensiveBlur;
  57729. },
  57730. set: function (b) {
  57731. 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"]);
  57732. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  57733. this._expensiveBlur = b;
  57734. this._firstUpdate = true;
  57735. },
  57736. enumerable: true,
  57737. configurable: true
  57738. });
  57739. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  57740. /**
  57741. * Support test.
  57742. * @type {boolean}
  57743. */
  57744. get: function () {
  57745. var engine = BABYLON.Engine.LastCreatedEngine;
  57746. if (!engine) {
  57747. return false;
  57748. }
  57749. return engine.getCaps().drawBuffersExtension;
  57750. },
  57751. enumerable: true,
  57752. configurable: true
  57753. });
  57754. // Public Methods
  57755. /**
  57756. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  57757. */
  57758. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  57759. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  57760. for (var i = 0; i < this._scene.cameras.length; i++) {
  57761. var camera = this._scene.cameras[i];
  57762. this._originalColorPostProcess.dispose(camera);
  57763. this._ssaoPostProcess.dispose(camera);
  57764. this._blurHPostProcess.dispose(camera);
  57765. this._blurVPostProcess.dispose(camera);
  57766. this._ssaoCombinePostProcess.dispose(camera);
  57767. }
  57768. this._randomTexture.dispose();
  57769. if (disableGeometryBufferRenderer)
  57770. this._scene.disableGeometryBufferRenderer();
  57771. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  57772. _super.prototype.dispose.call(this);
  57773. };
  57774. // Private Methods
  57775. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  57776. var _this = this;
  57777. this._samplerOffsets = [];
  57778. var expensive = this.expensiveBlur;
  57779. for (var i = -8; i < 8; i++) {
  57780. this._samplerOffsets.push(i * 2 + 0.5);
  57781. }
  57782. 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");
  57783. this._blurHPostProcess.onApply = function (effect) {
  57784. if (!_this._scene.activeCamera) {
  57785. return;
  57786. }
  57787. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  57788. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57789. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57790. effect.setFloat("radius", _this.radius);
  57791. effect.setTexture("depthSampler", _this._depthTexture);
  57792. if (_this._firstUpdate) {
  57793. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57794. }
  57795. };
  57796. 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");
  57797. this._blurVPostProcess.onApply = function (effect) {
  57798. if (!_this._scene.activeCamera) {
  57799. return;
  57800. }
  57801. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  57802. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57803. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57804. effect.setFloat("radius", _this.radius);
  57805. effect.setTexture("depthSampler", _this._depthTexture);
  57806. if (_this._firstUpdate) {
  57807. effect.setArray("samplerOffsets", _this._samplerOffsets);
  57808. _this._firstUpdate = false;
  57809. }
  57810. };
  57811. };
  57812. SSAO2RenderingPipeline.prototype._rebuild = function () {
  57813. this._firstUpdate = true;
  57814. _super.prototype._rebuild.call(this);
  57815. };
  57816. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  57817. var numSamples = this.samples;
  57818. var result = [];
  57819. var vector, scale;
  57820. var rand = function (min, max) {
  57821. return Math.random() * (max - min) + min;
  57822. };
  57823. var i = 0;
  57824. while (i < numSamples) {
  57825. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  57826. vector.normalize();
  57827. scale = i / numSamples;
  57828. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  57829. vector.scaleInPlace(scale);
  57830. result.push(vector.x, vector.y, vector.z);
  57831. i++;
  57832. }
  57833. return result;
  57834. };
  57835. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  57836. var _this = this;
  57837. var numSamples = this.samples;
  57838. this._sampleSphere = this._generateHemisphere();
  57839. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  57840. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  57841. "base", "range", "projection", "near", "far", "texelSize",
  57842. "xViewport", "yViewport", "maxZ", "minZAspect"
  57843. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  57844. this._ssaoPostProcess.onApply = function (effect) {
  57845. if (_this._firstUpdate) {
  57846. effect.setArray3("sampleSphere", _this._sampleSphere);
  57847. effect.setFloat("randTextureTiles", 4.0);
  57848. }
  57849. if (!_this._scene.activeCamera) {
  57850. return;
  57851. }
  57852. effect.setFloat("samplesFactor", 1 / _this.samples);
  57853. effect.setFloat("totalStrength", _this.totalStrength);
  57854. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  57855. effect.setFloat("radius", _this.radius);
  57856. effect.setFloat("maxZ", _this.maxZ);
  57857. effect.setFloat("minZAspect", _this.minZAspect);
  57858. effect.setFloat("base", _this.base);
  57859. effect.setFloat("near", _this._scene.activeCamera.minZ);
  57860. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  57861. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  57862. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  57863. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  57864. effect.setTexture("textureSampler", _this._depthTexture);
  57865. effect.setTexture("normalSampler", _this._normalTexture);
  57866. effect.setTexture("randomSampler", _this._randomTexture);
  57867. };
  57868. };
  57869. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  57870. var _this = this;
  57871. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  57872. this._ssaoCombinePostProcess.onApply = function (effect) {
  57873. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  57874. };
  57875. };
  57876. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  57877. var size = 512;
  57878. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  57879. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57880. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57881. var context = this._randomTexture.getContext();
  57882. var rand = function (min, max) {
  57883. return Math.random() * (max - min) + min;
  57884. };
  57885. var randVector = BABYLON.Vector3.Zero();
  57886. for (var x = 0; x < size; x++) {
  57887. for (var y = 0; y < size; y++) {
  57888. randVector.x = rand(0.0, 1.0);
  57889. randVector.y = rand(0.0, 1.0);
  57890. randVector.z = 0.0;
  57891. randVector.normalize();
  57892. randVector.scaleInPlace(255);
  57893. randVector.x = Math.floor(randVector.x);
  57894. randVector.y = Math.floor(randVector.y);
  57895. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  57896. context.fillRect(x, y, 1, 1);
  57897. }
  57898. }
  57899. this._randomTexture.update(false);
  57900. };
  57901. __decorate([
  57902. BABYLON.serialize()
  57903. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  57904. __decorate([
  57905. BABYLON.serialize()
  57906. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  57907. __decorate([
  57908. BABYLON.serialize()
  57909. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  57910. __decorate([
  57911. BABYLON.serialize("samples")
  57912. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  57913. __decorate([
  57914. BABYLON.serialize("expensiveBlur")
  57915. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  57916. __decorate([
  57917. BABYLON.serialize()
  57918. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  57919. __decorate([
  57920. BABYLON.serialize()
  57921. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  57922. __decorate([
  57923. BABYLON.serialize()
  57924. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  57925. return SSAO2RenderingPipeline;
  57926. }(BABYLON.PostProcessRenderPipeline));
  57927. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  57928. })(BABYLON || (BABYLON = {}));
  57929. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  57930. // BABYLON.JS Chromatic Aberration GLSL Shader
  57931. // Author: Olivier Guyot
  57932. // Separates very slightly R, G and B colors on the edges of the screen
  57933. // Inspired by Francois Tarlier & Martins Upitis
  57934. var BABYLON;
  57935. (function (BABYLON) {
  57936. var LensRenderingPipeline = /** @class */ (function (_super) {
  57937. __extends(LensRenderingPipeline, _super);
  57938. /**
  57939. * @constructor
  57940. *
  57941. * Effect parameters are as follow:
  57942. * {
  57943. * chromatic_aberration: number; // from 0 to x (1 for realism)
  57944. * edge_blur: number; // from 0 to x (1 for realism)
  57945. * distortion: number; // from 0 to x (1 for realism)
  57946. * grain_amount: number; // from 0 to 1
  57947. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  57948. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  57949. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  57950. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  57951. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  57952. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  57953. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  57954. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  57955. * }
  57956. * Note: if an effect parameter is unset, effect is disabled
  57957. *
  57958. * @param {string} name - The rendering pipeline name
  57959. * @param {object} parameters - An object containing all parameters (see above)
  57960. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  57961. * @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)
  57962. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  57963. */
  57964. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  57965. if (ratio === void 0) { ratio = 1.0; }
  57966. var _this = _super.call(this, scene.getEngine(), name) || this;
  57967. // Lens effects can be of the following:
  57968. // - chromatic aberration (slight shift of RGB colors)
  57969. // - blur on the edge of the lens
  57970. // - lens distortion
  57971. // - depth-of-field blur & highlights enhancing
  57972. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  57973. // - grain effect (noise or custom texture)
  57974. // Two additional texture samplers are needed:
  57975. // - depth map (for depth-of-field)
  57976. // - grain texture
  57977. /**
  57978. * The chromatic aberration PostProcess id in the pipeline
  57979. * @type {string}
  57980. */
  57981. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  57982. /**
  57983. * The highlights enhancing PostProcess id in the pipeline
  57984. * @type {string}
  57985. */
  57986. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  57987. /**
  57988. * The depth-of-field PostProcess id in the pipeline
  57989. * @type {string}
  57990. */
  57991. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  57992. _this._scene = scene;
  57993. // Fetch texture samplers
  57994. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  57995. if (parameters.grain_texture) {
  57996. _this._grainTexture = parameters.grain_texture;
  57997. }
  57998. else {
  57999. _this._createGrainTexture();
  58000. }
  58001. // save parameters
  58002. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  58003. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  58004. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  58005. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  58006. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  58007. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  58008. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  58009. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  58010. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  58011. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  58012. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  58013. // Create effects
  58014. _this._createChromaticAberrationPostProcess(ratio);
  58015. _this._createHighlightsPostProcess(ratio);
  58016. _this._createDepthOfFieldPostProcess(ratio / 4);
  58017. // Set up pipeline
  58018. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  58019. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  58020. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  58021. if (_this._highlightsGain === -1) {
  58022. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  58023. }
  58024. // Finish
  58025. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58026. if (cameras) {
  58027. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  58028. }
  58029. return _this;
  58030. }
  58031. // public methods (self explanatory)
  58032. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  58033. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  58034. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  58035. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  58036. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  58037. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  58038. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  58039. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  58040. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  58041. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  58042. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  58043. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  58044. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  58045. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  58046. };
  58047. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  58048. this._highlightsPostProcess.updateEffect();
  58049. };
  58050. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  58051. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  58052. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  58053. this._highlightsGain = amount;
  58054. };
  58055. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  58056. if (this._highlightsGain === -1) {
  58057. this._highlightsGain = 1.0;
  58058. }
  58059. this._highlightsThreshold = amount;
  58060. };
  58061. LensRenderingPipeline.prototype.disableHighlights = function () {
  58062. this._highlightsGain = -1;
  58063. };
  58064. /**
  58065. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  58066. */
  58067. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  58068. if (disableDepthRender === void 0) { disableDepthRender = false; }
  58069. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  58070. this._chromaticAberrationPostProcess = null;
  58071. this._highlightsPostProcess = null;
  58072. this._depthOfFieldPostProcess = null;
  58073. this._grainTexture.dispose();
  58074. if (disableDepthRender)
  58075. this._scene.disableDepthRenderer();
  58076. };
  58077. // colors shifting and distortion
  58078. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  58079. var _this = this;
  58080. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  58081. [], // samplers
  58082. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58083. this._chromaticAberrationPostProcess.onApply = function (effect) {
  58084. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  58085. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58086. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58087. };
  58088. };
  58089. // highlights enhancing
  58090. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  58091. var _this = this;
  58092. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  58093. [], // samplers
  58094. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  58095. this._highlightsPostProcess.onApply = function (effect) {
  58096. effect.setFloat('gain', _this._highlightsGain);
  58097. effect.setFloat('threshold', _this._highlightsThreshold);
  58098. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  58099. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58100. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58101. };
  58102. };
  58103. // colors shifting and distortion
  58104. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  58105. var _this = this;
  58106. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  58107. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  58108. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  58109. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  58110. this._depthOfFieldPostProcess.onApply = function (effect) {
  58111. effect.setTexture("depthSampler", _this._depthTexture);
  58112. effect.setTexture("grainSampler", _this._grainTexture);
  58113. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  58114. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  58115. effect.setFloat('grain_amount', _this._grainAmount);
  58116. effect.setBool('blur_noise', _this._blurNoise);
  58117. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  58118. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  58119. effect.setFloat('distortion', _this._distortion);
  58120. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  58121. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  58122. effect.setFloat('aperture', _this._dofAperture);
  58123. effect.setFloat('darken', _this._dofDarken);
  58124. effect.setFloat('edge_blur', _this._edgeBlur);
  58125. effect.setBool('highlights', (_this._highlightsGain !== -1));
  58126. if (_this._scene.activeCamera) {
  58127. effect.setFloat('near', _this._scene.activeCamera.minZ);
  58128. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  58129. }
  58130. };
  58131. };
  58132. // creates a black and white random noise texture, 512x512
  58133. LensRenderingPipeline.prototype._createGrainTexture = function () {
  58134. var size = 512;
  58135. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58136. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58137. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58138. var context = this._grainTexture.getContext();
  58139. var rand = function (min, max) {
  58140. return Math.random() * (max - min) + min;
  58141. };
  58142. var value;
  58143. for (var x = 0; x < size; x++) {
  58144. for (var y = 0; y < size; y++) {
  58145. value = Math.floor(rand(0.42, 0.58) * 255);
  58146. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  58147. context.fillRect(x, y, 1, 1);
  58148. }
  58149. }
  58150. this._grainTexture.update(false);
  58151. };
  58152. return LensRenderingPipeline;
  58153. }(BABYLON.PostProcessRenderPipeline));
  58154. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  58155. })(BABYLON || (BABYLON = {}));
  58156. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  58157. var BABYLON;
  58158. (function (BABYLON) {
  58159. var StandardRenderingPipeline = /** @class */ (function (_super) {
  58160. __extends(StandardRenderingPipeline, _super);
  58161. /**
  58162. * @constructor
  58163. * @param {string} name - The rendering pipeline name
  58164. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58165. * @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)
  58166. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  58167. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58168. */
  58169. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  58170. if (originalPostProcess === void 0) { originalPostProcess = null; }
  58171. var _this = _super.call(this, scene.getEngine(), name) || this;
  58172. _this.downSampleX4PostProcess = null;
  58173. _this.brightPassPostProcess = null;
  58174. _this.blurHPostProcesses = [];
  58175. _this.blurVPostProcesses = [];
  58176. _this.textureAdderPostProcess = null;
  58177. _this.volumetricLightPostProcess = null;
  58178. _this.volumetricLightSmoothXPostProcess = null;
  58179. _this.volumetricLightSmoothYPostProcess = null;
  58180. _this.volumetricLightMergePostProces = null;
  58181. _this.volumetricLightFinalPostProcess = null;
  58182. _this.luminancePostProcess = null;
  58183. _this.luminanceDownSamplePostProcesses = [];
  58184. _this.hdrPostProcess = null;
  58185. _this.textureAdderFinalPostProcess = null;
  58186. _this.lensFlareFinalPostProcess = null;
  58187. _this.hdrFinalPostProcess = null;
  58188. _this.lensFlarePostProcess = null;
  58189. _this.lensFlareComposePostProcess = null;
  58190. _this.motionBlurPostProcess = null;
  58191. _this.depthOfFieldPostProcess = null;
  58192. // Values
  58193. _this.brightThreshold = 1.0;
  58194. _this.blurWidth = 512.0;
  58195. _this.horizontalBlur = false;
  58196. _this.exposure = 1.0;
  58197. _this.lensTexture = null;
  58198. _this.volumetricLightCoefficient = 0.2;
  58199. _this.volumetricLightPower = 4.0;
  58200. _this.volumetricLightBlurScale = 64.0;
  58201. _this.sourceLight = null;
  58202. _this.hdrMinimumLuminance = 1.0;
  58203. _this.hdrDecreaseRate = 0.5;
  58204. _this.hdrIncreaseRate = 0.5;
  58205. _this.lensColorTexture = null;
  58206. _this.lensFlareStrength = 20.0;
  58207. _this.lensFlareGhostDispersal = 1.4;
  58208. _this.lensFlareHaloWidth = 0.7;
  58209. _this.lensFlareDistortionStrength = 16.0;
  58210. _this.lensStarTexture = null;
  58211. _this.lensFlareDirtTexture = null;
  58212. _this.depthOfFieldDistance = 10.0;
  58213. _this.depthOfFieldBlurWidth = 64.0;
  58214. _this.motionStrength = 1.0;
  58215. // IAnimatable
  58216. _this.animations = [];
  58217. _this._currentDepthOfFieldSource = null;
  58218. _this._hdrCurrentLuminance = 1.0;
  58219. // Getters and setters
  58220. _this._bloomEnabled = true;
  58221. _this._depthOfFieldEnabled = false;
  58222. _this._vlsEnabled = false;
  58223. _this._lensFlareEnabled = false;
  58224. _this._hdrEnabled = false;
  58225. _this._motionBlurEnabled = false;
  58226. _this._motionBlurSamples = 64.0;
  58227. _this._volumetricLightStepsCount = 50.0;
  58228. _this._cameras = cameras || [];
  58229. // Initialize
  58230. _this._scene = scene;
  58231. _this._basePostProcess = originalPostProcess;
  58232. _this._ratio = ratio;
  58233. // Misc
  58234. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58235. // Finish
  58236. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58237. _this._buildPipeline();
  58238. return _this;
  58239. }
  58240. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  58241. get: function () {
  58242. return this._bloomEnabled;
  58243. },
  58244. set: function (enabled) {
  58245. if (this._bloomEnabled === enabled) {
  58246. return;
  58247. }
  58248. this._bloomEnabled = enabled;
  58249. this._buildPipeline();
  58250. },
  58251. enumerable: true,
  58252. configurable: true
  58253. });
  58254. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  58255. get: function () {
  58256. return this._depthOfFieldEnabled;
  58257. },
  58258. set: function (enabled) {
  58259. if (this._depthOfFieldEnabled === enabled) {
  58260. return;
  58261. }
  58262. this._depthOfFieldEnabled = enabled;
  58263. this._buildPipeline();
  58264. },
  58265. enumerable: true,
  58266. configurable: true
  58267. });
  58268. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  58269. get: function () {
  58270. return this._lensFlareEnabled;
  58271. },
  58272. set: function (enabled) {
  58273. if (this._lensFlareEnabled === enabled) {
  58274. return;
  58275. }
  58276. this._lensFlareEnabled = enabled;
  58277. this._buildPipeline();
  58278. },
  58279. enumerable: true,
  58280. configurable: true
  58281. });
  58282. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  58283. get: function () {
  58284. return this._hdrEnabled;
  58285. },
  58286. set: function (enabled) {
  58287. if (this._hdrEnabled === enabled) {
  58288. return;
  58289. }
  58290. this._hdrEnabled = enabled;
  58291. this._buildPipeline();
  58292. },
  58293. enumerable: true,
  58294. configurable: true
  58295. });
  58296. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  58297. get: function () {
  58298. return this._vlsEnabled;
  58299. },
  58300. set: function (enabled) {
  58301. if (this._vlsEnabled === enabled) {
  58302. return;
  58303. }
  58304. if (enabled) {
  58305. var geometry = this._scene.enableGeometryBufferRenderer();
  58306. if (!geometry) {
  58307. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  58308. return;
  58309. }
  58310. }
  58311. this._vlsEnabled = enabled;
  58312. this._buildPipeline();
  58313. },
  58314. enumerable: true,
  58315. configurable: true
  58316. });
  58317. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  58318. get: function () {
  58319. return this._motionBlurEnabled;
  58320. },
  58321. set: function (enabled) {
  58322. if (this._motionBlurEnabled === enabled) {
  58323. return;
  58324. }
  58325. this._motionBlurEnabled = enabled;
  58326. this._buildPipeline();
  58327. },
  58328. enumerable: true,
  58329. configurable: true
  58330. });
  58331. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  58332. get: function () {
  58333. return this._volumetricLightStepsCount;
  58334. },
  58335. set: function (count) {
  58336. if (this.volumetricLightPostProcess) {
  58337. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  58338. }
  58339. this._volumetricLightStepsCount = count;
  58340. },
  58341. enumerable: true,
  58342. configurable: true
  58343. });
  58344. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  58345. get: function () {
  58346. return this._motionBlurSamples;
  58347. },
  58348. set: function (samples) {
  58349. if (this.motionBlurPostProcess) {
  58350. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  58351. }
  58352. this._motionBlurSamples = samples;
  58353. },
  58354. enumerable: true,
  58355. configurable: true
  58356. });
  58357. StandardRenderingPipeline.prototype._buildPipeline = function () {
  58358. var _this = this;
  58359. var ratio = this._ratio;
  58360. var scene = this._scene;
  58361. this._disposePostProcesses();
  58362. this._reset();
  58363. // Create pass post-process
  58364. if (!this._basePostProcess) {
  58365. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  58366. this.originalPostProcess.onApply = function (effect) {
  58367. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  58368. };
  58369. }
  58370. else {
  58371. this.originalPostProcess = this._basePostProcess;
  58372. }
  58373. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  58374. this._currentDepthOfFieldSource = this.originalPostProcess;
  58375. if (this._vlsEnabled) {
  58376. // Create volumetric light
  58377. this._createVolumetricLightPostProcess(scene, ratio);
  58378. // Create volumetric light final post-process
  58379. 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);
  58380. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  58381. }
  58382. if (this._bloomEnabled) {
  58383. // Create down sample X4 post-process
  58384. this._createDownSampleX4PostProcess(scene, ratio / 2);
  58385. // Create bright pass post-process
  58386. this._createBrightPassPostProcess(scene, ratio / 2);
  58387. // Create gaussian blur post-processes (down sampling blurs)
  58388. this._createBlurPostProcesses(scene, ratio / 4, 1);
  58389. // Create texture adder post-process
  58390. this._createTextureAdderPostProcess(scene, ratio);
  58391. // Create depth-of-field source post-process
  58392. 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);
  58393. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  58394. }
  58395. if (this._lensFlareEnabled) {
  58396. // Create lens flare post-process
  58397. this._createLensFlarePostProcess(scene, ratio);
  58398. // Create depth-of-field source post-process post lens-flare and disable it now
  58399. 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);
  58400. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  58401. }
  58402. if (this._hdrEnabled) {
  58403. // Create luminance
  58404. this._createLuminancePostProcesses(scene, this._floatTextureType);
  58405. // Create HDR
  58406. this._createHdrPostProcess(scene, ratio);
  58407. // Create depth-of-field source post-process post hdr and disable it now
  58408. 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);
  58409. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  58410. }
  58411. if (this._depthOfFieldEnabled) {
  58412. // Create gaussian blur used by depth-of-field
  58413. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  58414. // Create depth-of-field post-process
  58415. this._createDepthOfFieldPostProcess(scene, ratio);
  58416. }
  58417. if (this._motionBlurEnabled) {
  58418. // Create motion blur post-process
  58419. this._createMotionBlurPostProcess(scene, ratio);
  58420. }
  58421. if (this._cameras !== null) {
  58422. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  58423. }
  58424. };
  58425. // Down Sample X4 Post-Processs
  58426. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  58427. var _this = this;
  58428. var downSampleX4Offsets = new Array(32);
  58429. 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);
  58430. this.downSampleX4PostProcess.onApply = function (effect) {
  58431. var id = 0;
  58432. var width = _this.downSampleX4PostProcess.width;
  58433. var height = _this.downSampleX4PostProcess.height;
  58434. for (var i = -2; i < 2; i++) {
  58435. for (var j = -2; j < 2; j++) {
  58436. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  58437. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  58438. id += 2;
  58439. }
  58440. }
  58441. effect.setArray2("dsOffsets", downSampleX4Offsets);
  58442. };
  58443. // Add to pipeline
  58444. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  58445. };
  58446. // Brightpass Post-Process
  58447. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  58448. var _this = this;
  58449. var brightOffsets = new Array(8);
  58450. 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);
  58451. this.brightPassPostProcess.onApply = function (effect) {
  58452. var sU = (1.0 / _this.brightPassPostProcess.width);
  58453. var sV = (1.0 / _this.brightPassPostProcess.height);
  58454. brightOffsets[0] = -0.5 * sU;
  58455. brightOffsets[1] = 0.5 * sV;
  58456. brightOffsets[2] = 0.5 * sU;
  58457. brightOffsets[3] = 0.5 * sV;
  58458. brightOffsets[4] = -0.5 * sU;
  58459. brightOffsets[5] = -0.5 * sV;
  58460. brightOffsets[6] = 0.5 * sU;
  58461. brightOffsets[7] = -0.5 * sV;
  58462. effect.setArray2("dsOffsets", brightOffsets);
  58463. effect.setFloat("brightThreshold", _this.brightThreshold);
  58464. };
  58465. // Add to pipeline
  58466. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  58467. };
  58468. // Create blur H&V post-processes
  58469. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  58470. var _this = this;
  58471. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  58472. var engine = scene.getEngine();
  58473. 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);
  58474. 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);
  58475. blurX.onActivateObservable.add(function () {
  58476. var dw = blurX.width / engine.getRenderWidth();
  58477. blurX.kernel = _this[blurWidthKey] * dw;
  58478. });
  58479. blurY.onActivateObservable.add(function () {
  58480. var dw = blurY.height / engine.getRenderHeight();
  58481. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  58482. });
  58483. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  58484. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  58485. this.blurHPostProcesses.push(blurX);
  58486. this.blurVPostProcesses.push(blurY);
  58487. };
  58488. // Create texture adder post-process
  58489. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  58490. var _this = this;
  58491. 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);
  58492. this.textureAdderPostProcess.onApply = function (effect) {
  58493. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  58494. effect.setTexture("lensSampler", _this.lensTexture);
  58495. effect.setFloat("exposure", _this.exposure);
  58496. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  58497. };
  58498. // Add to pipeline
  58499. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  58500. };
  58501. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  58502. var _this = this;
  58503. var geometryRenderer = scene.enableGeometryBufferRenderer();
  58504. geometryRenderer.enablePosition = true;
  58505. var geometry = geometryRenderer.getGBuffer();
  58506. // Base post-process
  58507. 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));
  58508. var depthValues = BABYLON.Vector2.Zero();
  58509. this.volumetricLightPostProcess.onApply = function (effect) {
  58510. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  58511. var generator = _this.sourceLight.getShadowGenerator();
  58512. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  58513. effect.setTexture("positionSampler", geometry.textures[2]);
  58514. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  58515. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  58516. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  58517. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  58518. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  58519. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  58520. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  58521. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  58522. effect.setVector2("depthValues", depthValues);
  58523. }
  58524. };
  58525. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  58526. // Smooth
  58527. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  58528. // Merge
  58529. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  58530. this.volumetricLightMergePostProces.onApply = function (effect) {
  58531. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  58532. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  58533. };
  58534. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  58535. };
  58536. // Create luminance
  58537. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  58538. var _this = this;
  58539. // Create luminance
  58540. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  58541. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  58542. var offsets = [];
  58543. this.luminancePostProcess.onApply = function (effect) {
  58544. var sU = (1.0 / _this.luminancePostProcess.width);
  58545. var sV = (1.0 / _this.luminancePostProcess.height);
  58546. offsets[0] = -0.5 * sU;
  58547. offsets[1] = 0.5 * sV;
  58548. offsets[2] = 0.5 * sU;
  58549. offsets[3] = 0.5 * sV;
  58550. offsets[4] = -0.5 * sU;
  58551. offsets[5] = -0.5 * sV;
  58552. offsets[6] = 0.5 * sU;
  58553. offsets[7] = -0.5 * sV;
  58554. effect.setArray2("lumOffsets", offsets);
  58555. };
  58556. // Add to pipeline
  58557. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  58558. // Create down sample luminance
  58559. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  58560. var size = Math.pow(3, i);
  58561. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  58562. if (i === 0) {
  58563. defines += "#define FINAL_DOWN_SAMPLER";
  58564. }
  58565. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  58566. this.luminanceDownSamplePostProcesses.push(postProcess);
  58567. }
  58568. // Create callbacks and add effects
  58569. var lastLuminance = this.luminancePostProcess;
  58570. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  58571. var downSampleOffsets = new Array(18);
  58572. pp.onApply = function (effect) {
  58573. if (!lastLuminance) {
  58574. return;
  58575. }
  58576. var id = 0;
  58577. for (var x = -1; x < 2; x++) {
  58578. for (var y = -1; y < 2; y++) {
  58579. downSampleOffsets[id] = x / lastLuminance.width;
  58580. downSampleOffsets[id + 1] = y / lastLuminance.height;
  58581. id += 2;
  58582. }
  58583. }
  58584. effect.setArray2("dsOffsets", downSampleOffsets);
  58585. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  58586. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58587. lastLuminance = _this.luminancePostProcess;
  58588. }
  58589. else {
  58590. lastLuminance = pp;
  58591. }
  58592. };
  58593. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  58594. pp.onAfterRender = function (effect) {
  58595. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  58596. 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);
  58597. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  58598. };
  58599. }
  58600. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  58601. });
  58602. };
  58603. // Create HDR post-process
  58604. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  58605. var _this = this;
  58606. 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);
  58607. var outputLiminance = 1;
  58608. var time = 0;
  58609. var lastTime = 0;
  58610. this.hdrPostProcess.onApply = function (effect) {
  58611. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  58612. time += scene.getEngine().getDeltaTime();
  58613. if (outputLiminance < 0) {
  58614. outputLiminance = _this._hdrCurrentLuminance;
  58615. }
  58616. else {
  58617. var dt = (lastTime - time) / 1000.0;
  58618. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  58619. outputLiminance += _this.hdrDecreaseRate * dt;
  58620. }
  58621. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  58622. outputLiminance -= _this.hdrIncreaseRate * dt;
  58623. }
  58624. else {
  58625. outputLiminance = _this._hdrCurrentLuminance;
  58626. }
  58627. }
  58628. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  58629. effect.setFloat("averageLuminance", outputLiminance);
  58630. lastTime = time;
  58631. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  58632. };
  58633. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  58634. };
  58635. // Create lens flare post-process
  58636. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  58637. var _this = this;
  58638. 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);
  58639. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  58640. this._createBlurPostProcesses(scene, ratio / 4, 2);
  58641. 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);
  58642. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  58643. var resolution = new BABYLON.Vector2(0, 0);
  58644. // Lens flare
  58645. this.lensFlarePostProcess.onApply = function (effect) {
  58646. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  58647. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  58648. effect.setFloat("strength", _this.lensFlareStrength);
  58649. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  58650. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  58651. // Shift
  58652. resolution.x = _this.lensFlarePostProcess.width;
  58653. resolution.y = _this.lensFlarePostProcess.height;
  58654. effect.setVector2("resolution", resolution);
  58655. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  58656. };
  58657. // Compose
  58658. 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);
  58659. 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);
  58660. this.lensFlareComposePostProcess.onApply = function (effect) {
  58661. if (!_this._scene.activeCamera) {
  58662. return;
  58663. }
  58664. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58665. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  58666. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  58667. // Lens start rotation matrix
  58668. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  58669. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  58670. 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));
  58671. camRot *= 4.0;
  58672. 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);
  58673. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  58674. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  58675. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  58676. };
  58677. };
  58678. // Create depth-of-field post-process
  58679. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  58680. var _this = this;
  58681. 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);
  58682. this.depthOfFieldPostProcess.onApply = function (effect) {
  58683. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  58684. effect.setTexture("depthSampler", _this._getDepthTexture());
  58685. effect.setFloat("distance", _this.depthOfFieldDistance);
  58686. };
  58687. // Add to pipeline
  58688. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  58689. };
  58690. // Create motion blur post-process
  58691. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  58692. var _this = this;
  58693. 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);
  58694. var motionScale = 0;
  58695. var prevViewProjection = BABYLON.Matrix.Identity();
  58696. var invViewProjection = BABYLON.Matrix.Identity();
  58697. var viewProjection = BABYLON.Matrix.Identity();
  58698. var screenSize = BABYLON.Vector2.Zero();
  58699. this.motionBlurPostProcess.onApply = function (effect) {
  58700. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  58701. viewProjection.invertToRef(invViewProjection);
  58702. effect.setMatrix("inverseViewProjection", invViewProjection);
  58703. effect.setMatrix("prevViewProjection", prevViewProjection);
  58704. prevViewProjection = viewProjection;
  58705. screenSize.x = _this.motionBlurPostProcess.width;
  58706. screenSize.y = _this.motionBlurPostProcess.height;
  58707. effect.setVector2("screenSize", screenSize);
  58708. motionScale = scene.getEngine().getFps() / 60.0;
  58709. effect.setFloat("motionScale", motionScale);
  58710. effect.setFloat("motionStrength", _this.motionStrength);
  58711. effect.setTexture("depthSampler", _this._getDepthTexture());
  58712. };
  58713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  58714. };
  58715. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  58716. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  58717. var renderer = this._scene.enableGeometryBufferRenderer();
  58718. return renderer.getGBuffer().textures[0];
  58719. }
  58720. return this._scene.enableDepthRenderer().getDepthMap();
  58721. };
  58722. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  58723. for (var i = 0; i < this._cameras.length; i++) {
  58724. var camera = this._cameras[i];
  58725. if (this.originalPostProcess) {
  58726. this.originalPostProcess.dispose(camera);
  58727. }
  58728. if (this.downSampleX4PostProcess) {
  58729. this.downSampleX4PostProcess.dispose(camera);
  58730. }
  58731. if (this.brightPassPostProcess) {
  58732. this.brightPassPostProcess.dispose(camera);
  58733. }
  58734. if (this.textureAdderPostProcess) {
  58735. this.textureAdderPostProcess.dispose(camera);
  58736. }
  58737. if (this.textureAdderFinalPostProcess) {
  58738. this.textureAdderFinalPostProcess.dispose(camera);
  58739. }
  58740. if (this.volumetricLightPostProcess) {
  58741. this.volumetricLightPostProcess.dispose(camera);
  58742. }
  58743. if (this.volumetricLightSmoothXPostProcess) {
  58744. this.volumetricLightSmoothXPostProcess.dispose(camera);
  58745. }
  58746. if (this.volumetricLightSmoothYPostProcess) {
  58747. this.volumetricLightSmoothYPostProcess.dispose(camera);
  58748. }
  58749. if (this.volumetricLightMergePostProces) {
  58750. this.volumetricLightMergePostProces.dispose(camera);
  58751. }
  58752. if (this.volumetricLightFinalPostProcess) {
  58753. this.volumetricLightFinalPostProcess.dispose(camera);
  58754. }
  58755. if (this.lensFlarePostProcess) {
  58756. this.lensFlarePostProcess.dispose(camera);
  58757. }
  58758. if (this.lensFlareComposePostProcess) {
  58759. this.lensFlareComposePostProcess.dispose(camera);
  58760. }
  58761. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  58762. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  58763. }
  58764. if (this.luminancePostProcess) {
  58765. this.luminancePostProcess.dispose(camera);
  58766. }
  58767. if (this.hdrPostProcess) {
  58768. this.hdrPostProcess.dispose(camera);
  58769. }
  58770. if (this.hdrFinalPostProcess) {
  58771. this.hdrFinalPostProcess.dispose(camera);
  58772. }
  58773. if (this.depthOfFieldPostProcess) {
  58774. this.depthOfFieldPostProcess.dispose(camera);
  58775. }
  58776. if (this.motionBlurPostProcess) {
  58777. this.motionBlurPostProcess.dispose(camera);
  58778. }
  58779. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  58780. this.blurHPostProcesses[j].dispose(camera);
  58781. }
  58782. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  58783. this.blurVPostProcesses[j].dispose(camera);
  58784. }
  58785. }
  58786. this.originalPostProcess = null;
  58787. this.downSampleX4PostProcess = null;
  58788. this.brightPassPostProcess = null;
  58789. this.textureAdderPostProcess = null;
  58790. this.textureAdderFinalPostProcess = null;
  58791. this.volumetricLightPostProcess = null;
  58792. this.volumetricLightSmoothXPostProcess = null;
  58793. this.volumetricLightSmoothYPostProcess = null;
  58794. this.volumetricLightMergePostProces = null;
  58795. this.volumetricLightFinalPostProcess = null;
  58796. this.lensFlarePostProcess = null;
  58797. this.lensFlareComposePostProcess = null;
  58798. this.luminancePostProcess = null;
  58799. this.hdrPostProcess = null;
  58800. this.hdrFinalPostProcess = null;
  58801. this.depthOfFieldPostProcess = null;
  58802. this.motionBlurPostProcess = null;
  58803. this.luminanceDownSamplePostProcesses = [];
  58804. this.blurHPostProcesses = [];
  58805. this.blurVPostProcesses = [];
  58806. };
  58807. // Dispose
  58808. StandardRenderingPipeline.prototype.dispose = function () {
  58809. this._disposePostProcesses();
  58810. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  58811. _super.prototype.dispose.call(this);
  58812. };
  58813. // Serialize rendering pipeline
  58814. StandardRenderingPipeline.prototype.serialize = function () {
  58815. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  58816. serializationObject.customType = "StandardRenderingPipeline";
  58817. return serializationObject;
  58818. };
  58819. /**
  58820. * Static members
  58821. */
  58822. // Parse serialized pipeline
  58823. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  58824. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  58825. };
  58826. // Luminance steps
  58827. StandardRenderingPipeline.LuminanceSteps = 6;
  58828. __decorate([
  58829. BABYLON.serialize()
  58830. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  58831. __decorate([
  58832. BABYLON.serialize()
  58833. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  58834. __decorate([
  58835. BABYLON.serialize()
  58836. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  58837. __decorate([
  58838. BABYLON.serialize()
  58839. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  58840. __decorate([
  58841. BABYLON.serializeAsTexture("lensTexture")
  58842. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  58843. __decorate([
  58844. BABYLON.serialize()
  58845. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  58846. __decorate([
  58847. BABYLON.serialize()
  58848. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  58849. __decorate([
  58850. BABYLON.serialize()
  58851. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  58852. __decorate([
  58853. BABYLON.serialize()
  58854. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  58855. __decorate([
  58856. BABYLON.serialize()
  58857. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  58858. __decorate([
  58859. BABYLON.serialize()
  58860. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  58861. __decorate([
  58862. BABYLON.serializeAsTexture("lensColorTexture")
  58863. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  58864. __decorate([
  58865. BABYLON.serialize()
  58866. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  58867. __decorate([
  58868. BABYLON.serialize()
  58869. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  58870. __decorate([
  58871. BABYLON.serialize()
  58872. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  58873. __decorate([
  58874. BABYLON.serialize()
  58875. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  58876. __decorate([
  58877. BABYLON.serializeAsTexture("lensStarTexture")
  58878. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  58879. __decorate([
  58880. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  58881. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  58882. __decorate([
  58883. BABYLON.serialize()
  58884. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  58885. __decorate([
  58886. BABYLON.serialize()
  58887. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  58888. __decorate([
  58889. BABYLON.serialize()
  58890. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  58891. __decorate([
  58892. BABYLON.serialize()
  58893. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  58894. __decorate([
  58895. BABYLON.serialize()
  58896. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  58897. __decorate([
  58898. BABYLON.serialize()
  58899. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  58900. __decorate([
  58901. BABYLON.serialize()
  58902. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  58903. __decorate([
  58904. BABYLON.serialize()
  58905. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  58906. __decorate([
  58907. BABYLON.serialize()
  58908. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  58909. __decorate([
  58910. BABYLON.serialize()
  58911. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  58912. __decorate([
  58913. BABYLON.serialize()
  58914. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  58915. return StandardRenderingPipeline;
  58916. }(BABYLON.PostProcessRenderPipeline));
  58917. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  58918. })(BABYLON || (BABYLON = {}));
  58919. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  58920. var BABYLON;
  58921. (function (BABYLON) {
  58922. var FxaaPostProcess = /** @class */ (function (_super) {
  58923. __extends(FxaaPostProcess, _super);
  58924. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58925. if (camera === void 0) { camera = null; }
  58926. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58927. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  58928. _this.onApplyObservable.add(function (effect) {
  58929. var texelSize = _this.texelSize;
  58930. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  58931. });
  58932. return _this;
  58933. }
  58934. return FxaaPostProcess;
  58935. }(BABYLON.PostProcess));
  58936. BABYLON.FxaaPostProcess = FxaaPostProcess;
  58937. })(BABYLON || (BABYLON = {}));
  58938. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  58939. var BABYLON;
  58940. (function (BABYLON) {
  58941. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  58942. __extends(DefaultRenderingPipeline, _super);
  58943. /**
  58944. * @constructor
  58945. * @param {string} name - The rendering pipeline name
  58946. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  58947. * @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)
  58948. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  58949. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  58950. */
  58951. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  58952. if (automaticBuild === void 0) { automaticBuild = true; }
  58953. var _this = _super.call(this, scene.getEngine(), name) || this;
  58954. _this.PassPostProcessId = "PassPostProcessEffect";
  58955. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  58956. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  58957. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  58958. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  58959. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  58960. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  58961. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  58962. // IAnimatable
  58963. _this.animations = [];
  58964. // Values
  58965. _this._bloomEnabled = false;
  58966. _this._fxaaEnabled = false;
  58967. _this._imageProcessingEnabled = true;
  58968. _this._bloomScale = 0.6;
  58969. _this._buildAllowed = true;
  58970. /**
  58971. * Specifies the size of the bloom blur kernel, relative to the final output size
  58972. */
  58973. _this.bloomKernel = 64;
  58974. /**
  58975. * Specifies the weight of the bloom in the final rendering
  58976. */
  58977. _this._bloomWeight = 0.15;
  58978. _this._cameras = cameras || [];
  58979. _this._buildAllowed = automaticBuild;
  58980. // Initialize
  58981. _this._scene = scene;
  58982. var caps = _this._scene.getEngine().getCaps();
  58983. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  58984. // Misc
  58985. if (_this._hdr) {
  58986. if (caps.textureHalfFloatRender) {
  58987. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58988. }
  58989. else if (caps.textureFloatRender) {
  58990. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58991. }
  58992. }
  58993. else {
  58994. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58995. }
  58996. // Attach
  58997. scene.postProcessRenderPipelineManager.addPipeline(_this);
  58998. _this._buildPipeline();
  58999. return _this;
  59000. }
  59001. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  59002. get: function () {
  59003. return this._bloomWeight;
  59004. },
  59005. set: function (value) {
  59006. if (this._bloomWeight === value) {
  59007. return;
  59008. }
  59009. this._bloomWeight = value;
  59010. if (this._hdr && this.copyBack) {
  59011. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  59012. }
  59013. },
  59014. enumerable: true,
  59015. configurable: true
  59016. });
  59017. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  59018. get: function () {
  59019. return this._bloomScale;
  59020. },
  59021. set: function (value) {
  59022. if (this._bloomScale === value) {
  59023. return;
  59024. }
  59025. this._bloomScale = value;
  59026. this._buildPipeline();
  59027. },
  59028. enumerable: true,
  59029. configurable: true
  59030. });
  59031. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  59032. get: function () {
  59033. return this._bloomEnabled;
  59034. },
  59035. set: function (enabled) {
  59036. if (this._bloomEnabled === enabled) {
  59037. return;
  59038. }
  59039. this._bloomEnabled = enabled;
  59040. this._buildPipeline();
  59041. },
  59042. enumerable: true,
  59043. configurable: true
  59044. });
  59045. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  59046. get: function () {
  59047. return this._fxaaEnabled;
  59048. },
  59049. set: function (enabled) {
  59050. if (this._fxaaEnabled === enabled) {
  59051. return;
  59052. }
  59053. this._fxaaEnabled = enabled;
  59054. this._buildPipeline();
  59055. },
  59056. enumerable: true,
  59057. configurable: true
  59058. });
  59059. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  59060. get: function () {
  59061. return this._imageProcessingEnabled;
  59062. },
  59063. set: function (enabled) {
  59064. if (this._imageProcessingEnabled === enabled) {
  59065. return;
  59066. }
  59067. this._imageProcessingEnabled = enabled;
  59068. this._buildPipeline();
  59069. },
  59070. enumerable: true,
  59071. configurable: true
  59072. });
  59073. /**
  59074. * Force the compilation of the entire pipeline.
  59075. */
  59076. DefaultRenderingPipeline.prototype.prepare = function () {
  59077. var previousState = this._buildAllowed;
  59078. this._buildAllowed = true;
  59079. this._buildPipeline();
  59080. this._buildAllowed = previousState;
  59081. };
  59082. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  59083. var _this = this;
  59084. if (!this._buildAllowed) {
  59085. return;
  59086. }
  59087. var engine = this._scene.getEngine();
  59088. this._disposePostProcesses();
  59089. this._reset();
  59090. if (this.bloomEnabled) {
  59091. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59092. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  59093. if (!this._hdr) {
  59094. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59095. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  59096. this.highlights.autoClear = false;
  59097. this.highlights.alwaysForcePOT = true;
  59098. }
  59099. 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);
  59100. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  59101. this.blurX.alwaysForcePOT = true;
  59102. this.blurX.autoClear = false;
  59103. this.blurX.onActivateObservable.add(function () {
  59104. var dw = _this.blurX.width / engine.getRenderWidth(true);
  59105. _this.blurX.kernel = _this.bloomKernel * dw;
  59106. });
  59107. 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);
  59108. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  59109. this.blurY.alwaysForcePOT = true;
  59110. this.blurY.autoClear = false;
  59111. this.blurY.onActivateObservable.add(function () {
  59112. var dh = _this.blurY.height / engine.getRenderHeight(true);
  59113. _this.blurY.kernel = _this.bloomKernel * dh;
  59114. });
  59115. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59116. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  59117. this.copyBack.alwaysForcePOT = true;
  59118. if (this._hdr) {
  59119. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  59120. var w = this.bloomWeight;
  59121. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  59122. }
  59123. else {
  59124. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  59125. }
  59126. this.copyBack.autoClear = false;
  59127. }
  59128. if (this._imageProcessingEnabled) {
  59129. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59130. if (this._hdr) {
  59131. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  59132. }
  59133. else {
  59134. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  59135. }
  59136. }
  59137. if (this.fxaaEnabled) {
  59138. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59139. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  59140. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59141. }
  59142. else {
  59143. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  59144. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  59145. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  59146. }
  59147. if (this.bloomEnabled) {
  59148. if (this._hdr) {
  59149. this.copyBack.shareOutputWith(this.blurX);
  59150. if (this.imageProcessing) {
  59151. this.imageProcessing.shareOutputWith(this.pass);
  59152. this.imageProcessing.autoClear = false;
  59153. }
  59154. else if (this.fxaa) {
  59155. this.fxaa.shareOutputWith(this.pass);
  59156. }
  59157. else {
  59158. this.finalMerge.shareOutputWith(this.pass);
  59159. }
  59160. }
  59161. else {
  59162. if (this.fxaa) {
  59163. this.fxaa.shareOutputWith(this.pass);
  59164. }
  59165. else {
  59166. this.finalMerge.shareOutputWith(this.pass);
  59167. }
  59168. }
  59169. }
  59170. if (this._cameras !== null) {
  59171. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  59172. }
  59173. };
  59174. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  59175. for (var i = 0; i < this._cameras.length; i++) {
  59176. var camera = this._cameras[i];
  59177. if (this.pass) {
  59178. this.pass.dispose(camera);
  59179. }
  59180. if (this.highlights) {
  59181. this.highlights.dispose(camera);
  59182. }
  59183. if (this.blurX) {
  59184. this.blurX.dispose(camera);
  59185. }
  59186. if (this.blurY) {
  59187. this.blurY.dispose(camera);
  59188. }
  59189. if (this.copyBack) {
  59190. this.copyBack.dispose(camera);
  59191. }
  59192. if (this.imageProcessing) {
  59193. this.imageProcessing.dispose(camera);
  59194. }
  59195. if (this.fxaa) {
  59196. this.fxaa.dispose(camera);
  59197. }
  59198. if (this.finalMerge) {
  59199. this.finalMerge.dispose(camera);
  59200. }
  59201. }
  59202. this.pass = null;
  59203. this.highlights = null;
  59204. this.blurX = null;
  59205. this.blurY = null;
  59206. this.copyBack = null;
  59207. this.imageProcessing = null;
  59208. this.fxaa = null;
  59209. this.finalMerge = null;
  59210. };
  59211. // Dispose
  59212. DefaultRenderingPipeline.prototype.dispose = function () {
  59213. this._disposePostProcesses();
  59214. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  59215. _super.prototype.dispose.call(this);
  59216. };
  59217. // Serialize rendering pipeline
  59218. DefaultRenderingPipeline.prototype.serialize = function () {
  59219. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59220. serializationObject.customType = "DefaultRenderingPipeline";
  59221. return serializationObject;
  59222. };
  59223. // Parse serialized pipeline
  59224. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  59225. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  59226. };
  59227. __decorate([
  59228. BABYLON.serialize()
  59229. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  59230. __decorate([
  59231. BABYLON.serialize()
  59232. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  59233. __decorate([
  59234. BABYLON.serialize()
  59235. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  59236. __decorate([
  59237. BABYLON.serialize()
  59238. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  59239. __decorate([
  59240. BABYLON.serialize()
  59241. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  59242. __decorate([
  59243. BABYLON.serialize()
  59244. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  59245. __decorate([
  59246. BABYLON.serialize()
  59247. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  59248. __decorate([
  59249. BABYLON.serialize()
  59250. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  59251. return DefaultRenderingPipeline;
  59252. }(BABYLON.PostProcessRenderPipeline));
  59253. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  59254. })(BABYLON || (BABYLON = {}));
  59255. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  59256. var BABYLON;
  59257. (function (BABYLON) {
  59258. var GeometryBufferRenderer = /** @class */ (function () {
  59259. function GeometryBufferRenderer(scene, ratio) {
  59260. if (ratio === void 0) { ratio = 1; }
  59261. this._enablePosition = false;
  59262. this._scene = scene;
  59263. this._ratio = ratio;
  59264. // Render target
  59265. this._createRenderTargets();
  59266. }
  59267. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  59268. set: function (meshes) {
  59269. this._multiRenderTarget.renderList = meshes;
  59270. },
  59271. enumerable: true,
  59272. configurable: true
  59273. });
  59274. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  59275. get: function () {
  59276. return this._multiRenderTarget.isSupported;
  59277. },
  59278. enumerable: true,
  59279. configurable: true
  59280. });
  59281. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  59282. get: function () {
  59283. return this._enablePosition;
  59284. },
  59285. set: function (enable) {
  59286. this._enablePosition = enable;
  59287. this.dispose();
  59288. this._createRenderTargets();
  59289. },
  59290. enumerable: true,
  59291. configurable: true
  59292. });
  59293. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  59294. var material = subMesh.getMaterial();
  59295. if (material && material.disableDepthWrite) {
  59296. return false;
  59297. }
  59298. var defines = [];
  59299. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  59300. var mesh = subMesh.getMesh();
  59301. // Alpha test
  59302. if (material && material.needAlphaTesting()) {
  59303. defines.push("#define ALPHATEST");
  59304. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59305. attribs.push(BABYLON.VertexBuffer.UVKind);
  59306. defines.push("#define UV1");
  59307. }
  59308. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59309. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59310. defines.push("#define UV2");
  59311. }
  59312. }
  59313. // Buffers
  59314. if (this._enablePosition) {
  59315. defines.push("#define POSITION");
  59316. }
  59317. // Bones
  59318. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59319. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59320. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59321. if (mesh.numBoneInfluencers > 4) {
  59322. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59323. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59324. }
  59325. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59326. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59327. }
  59328. else {
  59329. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59330. }
  59331. // Instances
  59332. if (useInstances) {
  59333. defines.push("#define INSTANCES");
  59334. attribs.push("world0");
  59335. attribs.push("world1");
  59336. attribs.push("world2");
  59337. attribs.push("world3");
  59338. }
  59339. // Get correct effect
  59340. var join = defines.join("\n");
  59341. if (this._cachedDefines !== join) {
  59342. this._cachedDefines = join;
  59343. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  59344. }
  59345. return this._effect.isReady();
  59346. };
  59347. GeometryBufferRenderer.prototype.getGBuffer = function () {
  59348. return this._multiRenderTarget;
  59349. };
  59350. // Methods
  59351. GeometryBufferRenderer.prototype.dispose = function () {
  59352. this.getGBuffer().dispose();
  59353. };
  59354. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  59355. var _this = this;
  59356. var engine = this._scene.getEngine();
  59357. var count = this._enablePosition ? 3 : 2;
  59358. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  59359. if (!this.isSupported) {
  59360. return;
  59361. }
  59362. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59363. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59364. this._multiRenderTarget.refreshRate = 1;
  59365. this._multiRenderTarget.renderParticles = false;
  59366. this._multiRenderTarget.renderList = null;
  59367. // set default depth value to 1.0 (far away)
  59368. this._multiRenderTarget.onClearObservable.add(function (engine) {
  59369. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  59370. });
  59371. // Custom render function
  59372. var renderSubMesh = function (subMesh) {
  59373. var mesh = subMesh.getRenderingMesh();
  59374. var scene = _this._scene;
  59375. var engine = scene.getEngine();
  59376. var material = subMesh.getMaterial();
  59377. if (!material) {
  59378. return;
  59379. }
  59380. // Culling
  59381. engine.setState(material.backFaceCulling);
  59382. // Managing instances
  59383. var batch = mesh._getInstancesRenderList(subMesh._id);
  59384. if (batch.mustReturn) {
  59385. return;
  59386. }
  59387. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59388. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59389. engine.enableEffect(_this._effect);
  59390. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59391. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59392. _this._effect.setMatrix("view", scene.getViewMatrix());
  59393. // Alpha test
  59394. if (material && material.needAlphaTesting()) {
  59395. var alphaTexture = material.getAlphaTestTexture();
  59396. if (alphaTexture) {
  59397. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59398. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59399. }
  59400. }
  59401. // Bones
  59402. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59403. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59404. }
  59405. // Draw
  59406. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59407. }
  59408. };
  59409. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59410. var index;
  59411. if (depthOnlySubMeshes.length) {
  59412. engine.setColorWrite(false);
  59413. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59414. renderSubMesh(depthOnlySubMeshes.data[index]);
  59415. }
  59416. engine.setColorWrite(true);
  59417. }
  59418. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59419. renderSubMesh(opaqueSubMeshes.data[index]);
  59420. }
  59421. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59422. renderSubMesh(alphaTestSubMeshes.data[index]);
  59423. }
  59424. };
  59425. };
  59426. return GeometryBufferRenderer;
  59427. }());
  59428. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  59429. })(BABYLON || (BABYLON = {}));
  59430. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  59431. var BABYLON;
  59432. (function (BABYLON) {
  59433. var RefractionPostProcess = /** @class */ (function (_super) {
  59434. __extends(RefractionPostProcess, _super);
  59435. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  59436. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  59437. _this.color = color;
  59438. _this.depth = depth;
  59439. _this.colorLevel = colorLevel;
  59440. _this.onActivateObservable.add(function (cam) {
  59441. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  59442. });
  59443. _this.onApplyObservable.add(function (effect) {
  59444. effect.setColor3("baseColor", _this.color);
  59445. effect.setFloat("depth", _this.depth);
  59446. effect.setFloat("colorLevel", _this.colorLevel);
  59447. effect.setTexture("refractionSampler", _this._refRexture);
  59448. });
  59449. return _this;
  59450. }
  59451. // Methods
  59452. RefractionPostProcess.prototype.dispose = function (camera) {
  59453. if (this._refRexture) {
  59454. this._refRexture.dispose();
  59455. }
  59456. _super.prototype.dispose.call(this, camera);
  59457. };
  59458. return RefractionPostProcess;
  59459. }(BABYLON.PostProcess));
  59460. BABYLON.RefractionPostProcess = RefractionPostProcess;
  59461. })(BABYLON || (BABYLON = {}));
  59462. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  59463. var BABYLON;
  59464. (function (BABYLON) {
  59465. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  59466. __extends(BlackAndWhitePostProcess, _super);
  59467. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  59468. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  59469. _this.degree = 1;
  59470. _this.onApplyObservable.add(function (effect) {
  59471. effect.setFloat("degree", _this.degree);
  59472. });
  59473. return _this;
  59474. }
  59475. return BlackAndWhitePostProcess;
  59476. }(BABYLON.PostProcess));
  59477. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  59478. })(BABYLON || (BABYLON = {}));
  59479. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  59480. var BABYLON;
  59481. (function (BABYLON) {
  59482. var ConvolutionPostProcess = /** @class */ (function (_super) {
  59483. __extends(ConvolutionPostProcess, _super);
  59484. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  59485. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  59486. _this.kernel = kernel;
  59487. _this.onApply = function (effect) {
  59488. effect.setFloat2("screenSize", _this.width, _this.height);
  59489. effect.setArray("kernel", _this.kernel);
  59490. };
  59491. return _this;
  59492. }
  59493. // Statics
  59494. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  59495. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  59496. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  59497. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  59498. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  59499. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  59500. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  59501. return ConvolutionPostProcess;
  59502. }(BABYLON.PostProcess));
  59503. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  59504. })(BABYLON || (BABYLON = {}));
  59505. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  59506. var BABYLON;
  59507. (function (BABYLON) {
  59508. var FilterPostProcess = /** @class */ (function (_super) {
  59509. __extends(FilterPostProcess, _super);
  59510. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  59511. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  59512. _this.kernelMatrix = kernelMatrix;
  59513. _this.onApply = function (effect) {
  59514. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  59515. };
  59516. return _this;
  59517. }
  59518. return FilterPostProcess;
  59519. }(BABYLON.PostProcess));
  59520. BABYLON.FilterPostProcess = FilterPostProcess;
  59521. })(BABYLON || (BABYLON = {}));
  59522. //# sourceMappingURL=babylon.filterPostProcess.js.map
  59523. var BABYLON;
  59524. (function (BABYLON) {
  59525. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  59526. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  59527. __extends(VolumetricLightScatteringPostProcess, _super);
  59528. /**
  59529. * @constructor
  59530. * @param {string} name - The post-process name
  59531. * @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)
  59532. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  59533. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  59534. * @param {number} samples - The post-process quality, default 100
  59535. * @param {number} samplingMode - The post-process filtering mode
  59536. * @param {BABYLON.Engine} engine - The babylon engine
  59537. * @param {boolean} reusable - If the post-process is reusable
  59538. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  59539. */
  59540. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  59541. if (samples === void 0) { samples = 100; }
  59542. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59543. 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;
  59544. _this._screenCoordinates = BABYLON.Vector2.Zero();
  59545. /**
  59546. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  59547. * @type {Vector3}
  59548. */
  59549. _this.customMeshPosition = BABYLON.Vector3.Zero();
  59550. /**
  59551. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  59552. * @type {boolean}
  59553. */
  59554. _this.useCustomMeshPosition = false;
  59555. /**
  59556. * If the post-process should inverse the light scattering direction
  59557. * @type {boolean}
  59558. */
  59559. _this.invert = true;
  59560. /**
  59561. * Array containing the excluded meshes not rendered in the internal pass
  59562. */
  59563. _this.excludedMeshes = new Array();
  59564. /**
  59565. * Controls the overall intensity of the post-process
  59566. * @type {number}
  59567. */
  59568. _this.exposure = 0.3;
  59569. /**
  59570. * Dissipates each sample's contribution in range [0, 1]
  59571. * @type {number}
  59572. */
  59573. _this.decay = 0.96815;
  59574. /**
  59575. * Controls the overall intensity of each sample
  59576. * @type {number}
  59577. */
  59578. _this.weight = 0.58767;
  59579. /**
  59580. * Controls the density of each sample
  59581. * @type {number}
  59582. */
  59583. _this.density = 0.926;
  59584. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  59585. engine = scene.getEngine();
  59586. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  59587. // Configure mesh
  59588. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  59589. // Configure
  59590. _this._createPass(scene, ratio.passRatio || ratio);
  59591. _this.onActivate = function (camera) {
  59592. if (!_this.isSupported) {
  59593. _this.dispose(camera);
  59594. }
  59595. _this.onActivate = null;
  59596. };
  59597. _this.onApplyObservable.add(function (effect) {
  59598. _this._updateMeshScreenCoordinates(scene);
  59599. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  59600. effect.setFloat("exposure", _this.exposure);
  59601. effect.setFloat("decay", _this.decay);
  59602. effect.setFloat("weight", _this.weight);
  59603. effect.setFloat("density", _this.density);
  59604. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  59605. });
  59606. return _this;
  59607. }
  59608. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  59609. get: function () {
  59610. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59611. return false;
  59612. },
  59613. set: function (useDiffuseColor) {
  59614. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  59615. },
  59616. enumerable: true,
  59617. configurable: true
  59618. });
  59619. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  59620. return "VolumetricLightScatteringPostProcess";
  59621. };
  59622. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  59623. var mesh = subMesh.getMesh();
  59624. // Render this.mesh as default
  59625. if (mesh === this.mesh && mesh.material) {
  59626. return mesh.material.isReady(mesh);
  59627. }
  59628. var defines = [];
  59629. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59630. var material = subMesh.getMaterial();
  59631. // Alpha test
  59632. if (material) {
  59633. if (material.needAlphaTesting()) {
  59634. defines.push("#define ALPHATEST");
  59635. }
  59636. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59637. attribs.push(BABYLON.VertexBuffer.UVKind);
  59638. defines.push("#define UV1");
  59639. }
  59640. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59641. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59642. defines.push("#define UV2");
  59643. }
  59644. }
  59645. // Bones
  59646. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59647. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59648. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59649. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59650. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  59651. }
  59652. else {
  59653. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59654. }
  59655. // Instances
  59656. if (useInstances) {
  59657. defines.push("#define INSTANCES");
  59658. attribs.push("world0");
  59659. attribs.push("world1");
  59660. attribs.push("world2");
  59661. attribs.push("world3");
  59662. }
  59663. // Get correct effect
  59664. var join = defines.join("\n");
  59665. if (this._cachedDefines !== join) {
  59666. this._cachedDefines = join;
  59667. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  59668. }
  59669. return this._volumetricLightScatteringPass.isReady();
  59670. };
  59671. /**
  59672. * Sets the new light position for light scattering effect
  59673. * @param {BABYLON.Vector3} The new custom light position
  59674. */
  59675. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  59676. this.customMeshPosition = position;
  59677. };
  59678. /**
  59679. * Returns the light position for light scattering effect
  59680. * @return {BABYLON.Vector3} The custom light position
  59681. */
  59682. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  59683. return this.customMeshPosition;
  59684. };
  59685. /**
  59686. * Disposes the internal assets and detaches the post-process from the camera
  59687. */
  59688. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  59689. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  59690. if (rttIndex !== -1) {
  59691. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  59692. }
  59693. this._volumetricLightScatteringRTT.dispose();
  59694. _super.prototype.dispose.call(this, camera);
  59695. };
  59696. /**
  59697. * Returns the render target texture used by the post-process
  59698. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  59699. */
  59700. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  59701. return this._volumetricLightScatteringRTT;
  59702. };
  59703. // Private methods
  59704. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  59705. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  59706. return true;
  59707. }
  59708. return false;
  59709. };
  59710. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  59711. var _this = this;
  59712. var engine = scene.getEngine();
  59713. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59714. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59715. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59716. this._volumetricLightScatteringRTT.renderList = null;
  59717. this._volumetricLightScatteringRTT.renderParticles = false;
  59718. var camera = this.getCamera();
  59719. if (camera) {
  59720. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59721. }
  59722. else {
  59723. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  59724. }
  59725. // Custom render function for submeshes
  59726. var renderSubMesh = function (subMesh) {
  59727. var mesh = subMesh.getRenderingMesh();
  59728. if (_this._meshExcluded(mesh)) {
  59729. return;
  59730. }
  59731. var material = subMesh.getMaterial();
  59732. if (!material) {
  59733. return;
  59734. }
  59735. var scene = mesh.getScene();
  59736. var engine = scene.getEngine();
  59737. // Culling
  59738. engine.setState(material.backFaceCulling);
  59739. // Managing instances
  59740. var batch = mesh._getInstancesRenderList(subMesh._id);
  59741. if (batch.mustReturn) {
  59742. return;
  59743. }
  59744. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59745. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  59746. var effect = _this._volumetricLightScatteringPass;
  59747. if (mesh === _this.mesh) {
  59748. if (subMesh.effect) {
  59749. effect = subMesh.effect;
  59750. }
  59751. else {
  59752. effect = material.getEffect();
  59753. }
  59754. }
  59755. engine.enableEffect(effect);
  59756. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  59757. if (mesh === _this.mesh) {
  59758. material.bind(mesh.getWorldMatrix(), mesh);
  59759. }
  59760. else {
  59761. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  59762. // Alpha test
  59763. if (material && material.needAlphaTesting()) {
  59764. var alphaTexture = material.getAlphaTestTexture();
  59765. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  59766. if (alphaTexture) {
  59767. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59768. }
  59769. }
  59770. // Bones
  59771. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59772. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59773. }
  59774. }
  59775. // Draw
  59776. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  59777. }
  59778. };
  59779. // Render target texture callbacks
  59780. var savedSceneClearColor;
  59781. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  59782. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  59783. savedSceneClearColor = scene.clearColor;
  59784. scene.clearColor = sceneClearColor;
  59785. });
  59786. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  59787. scene.clearColor = savedSceneClearColor;
  59788. });
  59789. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59790. var engine = scene.getEngine();
  59791. var index;
  59792. if (depthOnlySubMeshes.length) {
  59793. engine.setColorWrite(false);
  59794. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59795. renderSubMesh(depthOnlySubMeshes.data[index]);
  59796. }
  59797. engine.setColorWrite(true);
  59798. }
  59799. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59800. renderSubMesh(opaqueSubMeshes.data[index]);
  59801. }
  59802. engine.setAlphaTesting(true);
  59803. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59804. renderSubMesh(alphaTestSubMeshes.data[index]);
  59805. }
  59806. engine.setAlphaTesting(false);
  59807. if (transparentSubMeshes.length) {
  59808. // Sort sub meshes
  59809. for (index = 0; index < transparentSubMeshes.length; index++) {
  59810. var submesh = transparentSubMeshes.data[index];
  59811. var boundingInfo = submesh.getBoundingInfo();
  59812. if (boundingInfo && scene.activeCamera) {
  59813. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  59814. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  59815. }
  59816. }
  59817. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  59818. sortedArray.sort(function (a, b) {
  59819. // Alpha index first
  59820. if (a._alphaIndex > b._alphaIndex) {
  59821. return 1;
  59822. }
  59823. if (a._alphaIndex < b._alphaIndex) {
  59824. return -1;
  59825. }
  59826. // Then distance to camera
  59827. if (a._distanceToCamera < b._distanceToCamera) {
  59828. return 1;
  59829. }
  59830. if (a._distanceToCamera > b._distanceToCamera) {
  59831. return -1;
  59832. }
  59833. return 0;
  59834. });
  59835. // Render sub meshes
  59836. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  59837. for (index = 0; index < sortedArray.length; index++) {
  59838. renderSubMesh(sortedArray[index]);
  59839. }
  59840. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59841. }
  59842. };
  59843. };
  59844. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  59845. var transform = scene.getTransformMatrix();
  59846. var meshPosition;
  59847. if (this.useCustomMeshPosition) {
  59848. meshPosition = this.customMeshPosition;
  59849. }
  59850. else if (this.attachedNode) {
  59851. meshPosition = this.attachedNode.position;
  59852. }
  59853. else {
  59854. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  59855. }
  59856. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  59857. this._screenCoordinates.x = pos.x / this._viewPort.width;
  59858. this._screenCoordinates.y = pos.y / this._viewPort.height;
  59859. if (this.invert)
  59860. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  59861. };
  59862. // Static methods
  59863. /**
  59864. * Creates a default mesh for the Volumeric Light Scattering post-process
  59865. * @param {string} The mesh name
  59866. * @param {BABYLON.Scene} The scene where to create the mesh
  59867. * @return {BABYLON.Mesh} the default mesh
  59868. */
  59869. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  59870. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  59871. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  59872. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  59873. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  59874. mesh.material = material;
  59875. return mesh;
  59876. };
  59877. __decorate([
  59878. BABYLON.serializeAsVector3()
  59879. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  59880. __decorate([
  59881. BABYLON.serialize()
  59882. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  59883. __decorate([
  59884. BABYLON.serialize()
  59885. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  59886. __decorate([
  59887. BABYLON.serializeAsMeshReference()
  59888. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  59889. __decorate([
  59890. BABYLON.serialize()
  59891. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  59892. __decorate([
  59893. BABYLON.serialize()
  59894. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  59895. __decorate([
  59896. BABYLON.serialize()
  59897. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  59898. __decorate([
  59899. BABYLON.serialize()
  59900. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  59901. __decorate([
  59902. BABYLON.serialize()
  59903. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  59904. return VolumetricLightScatteringPostProcess;
  59905. }(BABYLON.PostProcess));
  59906. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  59907. })(BABYLON || (BABYLON = {}));
  59908. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  59909. //
  59910. // This post-process allows the modification of rendered colors by using
  59911. // a 'look-up table' (LUT). This effect is also called Color Grading.
  59912. //
  59913. // The object needs to be provided an url to a texture containing the color
  59914. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  59915. // Use an image editing software to tweak the LUT to match your needs.
  59916. //
  59917. // For an example of a color LUT, see here:
  59918. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  59919. // For explanations on color grading, see here:
  59920. // http://udn.epicgames.com/Three/ColorGrading.html
  59921. //
  59922. var BABYLON;
  59923. (function (BABYLON) {
  59924. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  59925. __extends(ColorCorrectionPostProcess, _super);
  59926. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  59927. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  59928. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59929. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  59930. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59931. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59932. _this.onApply = function (effect) {
  59933. effect.setTexture("colorTable", _this._colorTableTexture);
  59934. };
  59935. return _this;
  59936. }
  59937. return ColorCorrectionPostProcess;
  59938. }(BABYLON.PostProcess));
  59939. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  59940. })(BABYLON || (BABYLON = {}));
  59941. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  59942. var BABYLON;
  59943. (function (BABYLON) {
  59944. var TonemappingOperator;
  59945. (function (TonemappingOperator) {
  59946. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  59947. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  59948. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  59949. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  59950. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  59951. ;
  59952. var TonemapPostProcess = /** @class */ (function (_super) {
  59953. __extends(TonemapPostProcess, _super);
  59954. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  59955. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59956. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59957. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  59958. _this._operator = _operator;
  59959. _this.exposureAdjustment = exposureAdjustment;
  59960. var defines = "#define ";
  59961. if (_this._operator === TonemappingOperator.Hable)
  59962. defines += "HABLE_TONEMAPPING";
  59963. else if (_this._operator === TonemappingOperator.Reinhard)
  59964. defines += "REINHARD_TONEMAPPING";
  59965. else if (_this._operator === TonemappingOperator.HejiDawson)
  59966. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  59967. else if (_this._operator === TonemappingOperator.Photographic)
  59968. defines += "PHOTOGRAPHIC_TONEMAPPING";
  59969. //sadly a second call to create the effect.
  59970. _this.updateEffect(defines);
  59971. _this.onApply = function (effect) {
  59972. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  59973. };
  59974. return _this;
  59975. }
  59976. return TonemapPostProcess;
  59977. }(BABYLON.PostProcess));
  59978. BABYLON.TonemapPostProcess = TonemapPostProcess;
  59979. })(BABYLON || (BABYLON = {}));
  59980. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  59981. var BABYLON;
  59982. (function (BABYLON) {
  59983. var DisplayPassPostProcess = /** @class */ (function (_super) {
  59984. __extends(DisplayPassPostProcess, _super);
  59985. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  59986. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  59987. }
  59988. return DisplayPassPostProcess;
  59989. }(BABYLON.PostProcess));
  59990. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  59991. })(BABYLON || (BABYLON = {}));
  59992. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  59993. var BABYLON;
  59994. (function (BABYLON) {
  59995. var HighlightsPostProcess = /** @class */ (function (_super) {
  59996. __extends(HighlightsPostProcess, _super);
  59997. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59998. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59999. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  60000. }
  60001. return HighlightsPostProcess;
  60002. }(BABYLON.PostProcess));
  60003. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  60004. })(BABYLON || (BABYLON = {}));
  60005. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  60006. var BABYLON;
  60007. (function (BABYLON) {
  60008. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  60009. __extends(ImageProcessingPostProcess, _super);
  60010. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60011. if (camera === void 0) { camera = null; }
  60012. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60013. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  60014. _this._fromLinearSpace = true;
  60015. /**
  60016. * Defines cache preventing GC.
  60017. */
  60018. _this._defines = {
  60019. IMAGEPROCESSING: false,
  60020. VIGNETTE: false,
  60021. VIGNETTEBLENDMODEMULTIPLY: false,
  60022. VIGNETTEBLENDMODEOPAQUE: false,
  60023. TONEMAPPING: false,
  60024. CONTRAST: false,
  60025. COLORCURVES: false,
  60026. COLORGRADING: false,
  60027. COLORGRADING3D: false,
  60028. FROMLINEARSPACE: false,
  60029. SAMPLER3DGREENDEPTH: false,
  60030. SAMPLER3DBGRMAP: false,
  60031. IMAGEPROCESSINGPOSTPROCESS: false,
  60032. EXPOSURE: false,
  60033. };
  60034. // Setup the default processing configuration to the scene.
  60035. _this._attachImageProcessingConfiguration(null, true);
  60036. _this.imageProcessingConfiguration.applyByPostProcess = true;
  60037. _this.onApply = function (effect) {
  60038. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  60039. };
  60040. return _this;
  60041. }
  60042. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  60043. /**
  60044. * Gets the image processing configuration used either in this material.
  60045. */
  60046. get: function () {
  60047. return this._imageProcessingConfiguration;
  60048. },
  60049. /**
  60050. * Sets the Default image processing configuration used either in the this material.
  60051. *
  60052. * If sets to null, the scene one is in use.
  60053. */
  60054. set: function (value) {
  60055. this._attachImageProcessingConfiguration(value);
  60056. },
  60057. enumerable: true,
  60058. configurable: true
  60059. });
  60060. /**
  60061. * Attaches a new image processing configuration to the PBR Material.
  60062. * @param configuration
  60063. */
  60064. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  60065. var _this = this;
  60066. if (doNotBuild === void 0) { doNotBuild = false; }
  60067. if (configuration === this._imageProcessingConfiguration) {
  60068. return;
  60069. }
  60070. // Detaches observer.
  60071. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60072. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60073. }
  60074. // Pick the scene configuration if needed.
  60075. if (!configuration) {
  60076. var scene = null;
  60077. var engine = this.getEngine();
  60078. var camera = this.getCamera();
  60079. if (camera) {
  60080. scene = camera.getScene();
  60081. }
  60082. else if (engine && engine.scenes) {
  60083. var scenes = engine.scenes;
  60084. scene = scenes[scenes.length - 1];
  60085. }
  60086. else {
  60087. scene = BABYLON.Engine.LastCreatedScene;
  60088. }
  60089. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  60090. }
  60091. else {
  60092. this._imageProcessingConfiguration = configuration;
  60093. }
  60094. // Attaches observer.
  60095. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  60096. _this._updateParameters();
  60097. });
  60098. // Ensure the effect will be rebuilt.
  60099. if (!doNotBuild) {
  60100. this._updateParameters();
  60101. }
  60102. };
  60103. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  60104. /**
  60105. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60106. */
  60107. get: function () {
  60108. return this.imageProcessingConfiguration.colorCurves;
  60109. },
  60110. /**
  60111. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  60112. */
  60113. set: function (value) {
  60114. this.imageProcessingConfiguration.colorCurves = value;
  60115. },
  60116. enumerable: true,
  60117. configurable: true
  60118. });
  60119. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  60120. /**
  60121. * Gets wether the color curves effect is enabled.
  60122. */
  60123. get: function () {
  60124. return this.imageProcessingConfiguration.colorCurvesEnabled;
  60125. },
  60126. /**
  60127. * Sets wether the color curves effect is enabled.
  60128. */
  60129. set: function (value) {
  60130. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  60131. },
  60132. enumerable: true,
  60133. configurable: true
  60134. });
  60135. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  60136. /**
  60137. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60138. */
  60139. get: function () {
  60140. return this.imageProcessingConfiguration.colorGradingTexture;
  60141. },
  60142. /**
  60143. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  60144. */
  60145. set: function (value) {
  60146. this.imageProcessingConfiguration.colorGradingTexture = value;
  60147. },
  60148. enumerable: true,
  60149. configurable: true
  60150. });
  60151. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  60152. /**
  60153. * Gets wether the color grading effect is enabled.
  60154. */
  60155. get: function () {
  60156. return this.imageProcessingConfiguration.colorGradingEnabled;
  60157. },
  60158. /**
  60159. * Gets wether the color grading effect is enabled.
  60160. */
  60161. set: function (value) {
  60162. this.imageProcessingConfiguration.colorGradingEnabled = value;
  60163. },
  60164. enumerable: true,
  60165. configurable: true
  60166. });
  60167. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  60168. /**
  60169. * Gets exposure used in the effect.
  60170. */
  60171. get: function () {
  60172. return this.imageProcessingConfiguration.exposure;
  60173. },
  60174. /**
  60175. * Sets exposure used in the effect.
  60176. */
  60177. set: function (value) {
  60178. this.imageProcessingConfiguration.exposure = value;
  60179. },
  60180. enumerable: true,
  60181. configurable: true
  60182. });
  60183. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  60184. /**
  60185. * Gets wether tonemapping is enabled or not.
  60186. */
  60187. get: function () {
  60188. return this._imageProcessingConfiguration.toneMappingEnabled;
  60189. },
  60190. /**
  60191. * Sets wether tonemapping is enabled or not
  60192. */
  60193. set: function (value) {
  60194. this._imageProcessingConfiguration.toneMappingEnabled = value;
  60195. },
  60196. enumerable: true,
  60197. configurable: true
  60198. });
  60199. ;
  60200. ;
  60201. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  60202. /**
  60203. * Gets contrast used in the effect.
  60204. */
  60205. get: function () {
  60206. return this.imageProcessingConfiguration.contrast;
  60207. },
  60208. /**
  60209. * Sets contrast used in the effect.
  60210. */
  60211. set: function (value) {
  60212. this.imageProcessingConfiguration.contrast = value;
  60213. },
  60214. enumerable: true,
  60215. configurable: true
  60216. });
  60217. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  60218. /**
  60219. * Gets Vignette stretch size.
  60220. */
  60221. get: function () {
  60222. return this.imageProcessingConfiguration.vignetteStretch;
  60223. },
  60224. /**
  60225. * Sets Vignette stretch size.
  60226. */
  60227. set: function (value) {
  60228. this.imageProcessingConfiguration.vignetteStretch = value;
  60229. },
  60230. enumerable: true,
  60231. configurable: true
  60232. });
  60233. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  60234. /**
  60235. * Gets Vignette centre X Offset.
  60236. */
  60237. get: function () {
  60238. return this.imageProcessingConfiguration.vignetteCentreX;
  60239. },
  60240. /**
  60241. * Sets Vignette centre X Offset.
  60242. */
  60243. set: function (value) {
  60244. this.imageProcessingConfiguration.vignetteCentreX = value;
  60245. },
  60246. enumerable: true,
  60247. configurable: true
  60248. });
  60249. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  60250. /**
  60251. * Gets Vignette centre Y Offset.
  60252. */
  60253. get: function () {
  60254. return this.imageProcessingConfiguration.vignetteCentreY;
  60255. },
  60256. /**
  60257. * Sets Vignette centre Y Offset.
  60258. */
  60259. set: function (value) {
  60260. this.imageProcessingConfiguration.vignetteCentreY = value;
  60261. },
  60262. enumerable: true,
  60263. configurable: true
  60264. });
  60265. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  60266. /**
  60267. * Gets Vignette weight or intensity of the vignette effect.
  60268. */
  60269. get: function () {
  60270. return this.imageProcessingConfiguration.vignetteWeight;
  60271. },
  60272. /**
  60273. * Sets Vignette weight or intensity of the vignette effect.
  60274. */
  60275. set: function (value) {
  60276. this.imageProcessingConfiguration.vignetteWeight = value;
  60277. },
  60278. enumerable: true,
  60279. configurable: true
  60280. });
  60281. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  60282. /**
  60283. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60284. * if vignetteEnabled is set to true.
  60285. */
  60286. get: function () {
  60287. return this.imageProcessingConfiguration.vignetteColor;
  60288. },
  60289. /**
  60290. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  60291. * if vignetteEnabled is set to true.
  60292. */
  60293. set: function (value) {
  60294. this.imageProcessingConfiguration.vignetteColor = value;
  60295. },
  60296. enumerable: true,
  60297. configurable: true
  60298. });
  60299. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  60300. /**
  60301. * Gets Camera field of view used by the Vignette effect.
  60302. */
  60303. get: function () {
  60304. return this.imageProcessingConfiguration.vignetteCameraFov;
  60305. },
  60306. /**
  60307. * Sets Camera field of view used by the Vignette effect.
  60308. */
  60309. set: function (value) {
  60310. this.imageProcessingConfiguration.vignetteCameraFov = value;
  60311. },
  60312. enumerable: true,
  60313. configurable: true
  60314. });
  60315. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  60316. /**
  60317. * Gets the vignette blend mode allowing different kind of effect.
  60318. */
  60319. get: function () {
  60320. return this.imageProcessingConfiguration.vignetteBlendMode;
  60321. },
  60322. /**
  60323. * Sets the vignette blend mode allowing different kind of effect.
  60324. */
  60325. set: function (value) {
  60326. this.imageProcessingConfiguration.vignetteBlendMode = value;
  60327. },
  60328. enumerable: true,
  60329. configurable: true
  60330. });
  60331. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  60332. /**
  60333. * Gets wether the vignette effect is enabled.
  60334. */
  60335. get: function () {
  60336. return this.imageProcessingConfiguration.vignetteEnabled;
  60337. },
  60338. /**
  60339. * Sets wether the vignette effect is enabled.
  60340. */
  60341. set: function (value) {
  60342. this.imageProcessingConfiguration.vignetteEnabled = value;
  60343. },
  60344. enumerable: true,
  60345. configurable: true
  60346. });
  60347. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  60348. /**
  60349. * Gets wether the input of the processing is in Gamma or Linear Space.
  60350. */
  60351. get: function () {
  60352. return this._fromLinearSpace;
  60353. },
  60354. /**
  60355. * Sets wether the input of the processing is in Gamma or Linear Space.
  60356. */
  60357. set: function (value) {
  60358. if (this._fromLinearSpace === value) {
  60359. return;
  60360. }
  60361. this._fromLinearSpace = value;
  60362. this._updateParameters();
  60363. },
  60364. enumerable: true,
  60365. configurable: true
  60366. });
  60367. ImageProcessingPostProcess.prototype.getClassName = function () {
  60368. return "ImageProcessingPostProcess";
  60369. };
  60370. ImageProcessingPostProcess.prototype._updateParameters = function () {
  60371. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  60372. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  60373. var defines = "";
  60374. for (var define in this._defines) {
  60375. if (this._defines[define]) {
  60376. defines += "#define " + define + ";\r\n";
  60377. }
  60378. }
  60379. var samplers = ["textureSampler"];
  60380. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  60381. var uniforms = ["scale"];
  60382. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  60383. this.updateEffect(defines, uniforms, samplers);
  60384. };
  60385. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  60386. _super.prototype.dispose.call(this, camera);
  60387. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  60388. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  60389. }
  60390. this.imageProcessingConfiguration.applyByPostProcess = false;
  60391. };
  60392. __decorate([
  60393. BABYLON.serialize()
  60394. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  60395. return ImageProcessingPostProcess;
  60396. }(BABYLON.PostProcess));
  60397. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  60398. })(BABYLON || (BABYLON = {}));
  60399. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  60400. var BABYLON;
  60401. (function (BABYLON) {
  60402. var BlurPostProcess = /** @class */ (function (_super) {
  60403. __extends(BlurPostProcess, _super);
  60404. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  60405. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60406. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60407. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  60408. _this.direction = direction;
  60409. _this._packedFloat = false;
  60410. _this.onApplyObservable.add(function (effect) {
  60411. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  60412. });
  60413. _this.kernel = kernel;
  60414. return _this;
  60415. }
  60416. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  60417. /**
  60418. * Gets the length in pixels of the blur sample region
  60419. */
  60420. get: function () {
  60421. return this._idealKernel;
  60422. },
  60423. /**
  60424. * Sets the length in pixels of the blur sample region
  60425. */
  60426. set: function (v) {
  60427. if (this._idealKernel === v) {
  60428. return;
  60429. }
  60430. v = Math.max(v, 1);
  60431. this._idealKernel = v;
  60432. this._kernel = this._nearestBestKernel(v);
  60433. this._updateParameters();
  60434. },
  60435. enumerable: true,
  60436. configurable: true
  60437. });
  60438. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  60439. /**
  60440. * Gets wether or not the blur is unpacking/repacking floats
  60441. */
  60442. get: function () {
  60443. return this._packedFloat;
  60444. },
  60445. /**
  60446. * Sets wether or not the blur needs to unpack/repack floats
  60447. */
  60448. set: function (v) {
  60449. if (this._packedFloat === v) {
  60450. return;
  60451. }
  60452. this._packedFloat = v;
  60453. this._updateParameters();
  60454. },
  60455. enumerable: true,
  60456. configurable: true
  60457. });
  60458. BlurPostProcess.prototype._updateParameters = function () {
  60459. // Generate sampling offsets and weights
  60460. var N = this._kernel;
  60461. var centerIndex = (N - 1) / 2;
  60462. // Generate Gaussian sampling weights over kernel
  60463. var offsets = [];
  60464. var weights = [];
  60465. var totalWeight = 0;
  60466. for (var i = 0; i < N; i++) {
  60467. var u = i / (N - 1);
  60468. var w = this._gaussianWeight(u * 2.0 - 1);
  60469. offsets[i] = (i - centerIndex);
  60470. weights[i] = w;
  60471. totalWeight += w;
  60472. }
  60473. // Normalize weights
  60474. for (var i = 0; i < weights.length; i++) {
  60475. weights[i] /= totalWeight;
  60476. }
  60477. // Optimize: combine samples to take advantage of hardware linear sampling
  60478. // Walk from left to center, combining pairs (symmetrically)
  60479. var linearSamplingWeights = [];
  60480. var linearSamplingOffsets = [];
  60481. var linearSamplingMap = [];
  60482. for (var i = 0; i <= centerIndex; i += 2) {
  60483. var j = Math.min(i + 1, Math.floor(centerIndex));
  60484. var singleCenterSample = i === j;
  60485. if (singleCenterSample) {
  60486. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60487. }
  60488. else {
  60489. var sharedCell = j === centerIndex;
  60490. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  60491. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  60492. if (offsetLinear === 0) {
  60493. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  60494. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  60495. }
  60496. else {
  60497. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  60498. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  60499. }
  60500. }
  60501. }
  60502. for (var i = 0; i < linearSamplingMap.length; i++) {
  60503. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  60504. linearSamplingWeights[i] = linearSamplingMap[i].w;
  60505. }
  60506. // Replace with optimized
  60507. offsets = linearSamplingOffsets;
  60508. weights = linearSamplingWeights;
  60509. // Generate shaders
  60510. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  60511. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  60512. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  60513. var defines = "";
  60514. for (var i = 0; i < varyingCount; i++) {
  60515. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  60516. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  60517. }
  60518. var depCount = 0;
  60519. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  60520. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  60521. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  60522. depCount++;
  60523. }
  60524. if (this.packedFloat) {
  60525. defines += "#define PACKEDFLOAT 1";
  60526. }
  60527. this.updateEffect(defines, null, null, {
  60528. varyingCount: varyingCount,
  60529. depCount: depCount
  60530. });
  60531. };
  60532. /**
  60533. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  60534. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  60535. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  60536. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  60537. * The gaps between physical kernels are compensated for in the weighting of the samples
  60538. * @param idealKernel Ideal blur kernel.
  60539. * @return Nearest best kernel.
  60540. */
  60541. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  60542. var v = Math.round(idealKernel);
  60543. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  60544. var k = _a[_i];
  60545. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  60546. return Math.max(k, 3);
  60547. }
  60548. }
  60549. return Math.max(v, 3);
  60550. };
  60551. /**
  60552. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  60553. * @param x The point on the Gaussian distribution to sample.
  60554. * @return the value of the Gaussian function at x.
  60555. */
  60556. BlurPostProcess.prototype._gaussianWeight = function (x) {
  60557. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  60558. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  60559. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  60560. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  60561. // truncated at around 1.3% of peak strength.
  60562. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  60563. var sigma = (1 / 3);
  60564. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  60565. var exponent = -((x * x) / (2.0 * sigma * sigma));
  60566. var weight = (1.0 / denominator) * Math.exp(exponent);
  60567. return weight;
  60568. };
  60569. /**
  60570. * Generates a string that can be used as a floating point number in GLSL.
  60571. * @param x Value to print.
  60572. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  60573. * @return GLSL float string.
  60574. */
  60575. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  60576. if (decimalFigures === void 0) { decimalFigures = 8; }
  60577. return x.toFixed(decimalFigures).replace(/0+$/, '');
  60578. };
  60579. return BlurPostProcess;
  60580. }(BABYLON.PostProcess));
  60581. BABYLON.BlurPostProcess = BlurPostProcess;
  60582. })(BABYLON || (BABYLON = {}));
  60583. //# sourceMappingURL=babylon.blurPostProcess.js.map
  60584. var BABYLON;
  60585. (function (BABYLON) {
  60586. var Bone = /** @class */ (function (_super) {
  60587. __extends(Bone, _super);
  60588. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  60589. if (parentBone === void 0) { parentBone = null; }
  60590. if (localMatrix === void 0) { localMatrix = null; }
  60591. if (restPose === void 0) { restPose = null; }
  60592. if (baseMatrix === void 0) { baseMatrix = null; }
  60593. if (index === void 0) { index = null; }
  60594. var _this = _super.call(this, name, skeleton.getScene()) || this;
  60595. _this.name = name;
  60596. _this.children = new Array();
  60597. _this.animations = new Array();
  60598. // Set this value to map this bone to a different index in the transform matrices.
  60599. // Set this value to -1 to exclude the bone from the transform matrices.
  60600. _this._index = null;
  60601. _this._worldTransform = new BABYLON.Matrix();
  60602. _this._absoluteTransform = new BABYLON.Matrix();
  60603. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  60604. _this._scaleMatrix = BABYLON.Matrix.Identity();
  60605. _this._scaleVector = BABYLON.Vector3.One();
  60606. _this._negateScaleChildren = BABYLON.Vector3.One();
  60607. _this._scalingDeterminant = 1;
  60608. _this._skeleton = skeleton;
  60609. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  60610. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  60611. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  60612. _this._index = index;
  60613. skeleton.bones.push(_this);
  60614. _this.setParent(parentBone, false);
  60615. _this._updateDifferenceMatrix();
  60616. return _this;
  60617. }
  60618. Object.defineProperty(Bone.prototype, "_matrix", {
  60619. get: function () {
  60620. return this._localMatrix;
  60621. },
  60622. set: function (val) {
  60623. if (this._localMatrix) {
  60624. this._localMatrix.copyFrom(val);
  60625. }
  60626. else {
  60627. this._localMatrix = val;
  60628. }
  60629. },
  60630. enumerable: true,
  60631. configurable: true
  60632. });
  60633. // Members
  60634. Bone.prototype.getSkeleton = function () {
  60635. return this._skeleton;
  60636. };
  60637. Bone.prototype.getParent = function () {
  60638. return this._parent;
  60639. };
  60640. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  60641. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60642. if (this._parent === parent) {
  60643. return;
  60644. }
  60645. if (this._parent) {
  60646. var index = this._parent.children.indexOf(this);
  60647. if (index !== -1) {
  60648. this._parent.children.splice(index, 1);
  60649. }
  60650. }
  60651. this._parent = parent;
  60652. if (this._parent) {
  60653. this._parent.children.push(this);
  60654. }
  60655. if (updateDifferenceMatrix) {
  60656. this._updateDifferenceMatrix();
  60657. }
  60658. };
  60659. Bone.prototype.getLocalMatrix = function () {
  60660. return this._localMatrix;
  60661. };
  60662. Bone.prototype.getBaseMatrix = function () {
  60663. return this._baseMatrix;
  60664. };
  60665. Bone.prototype.getRestPose = function () {
  60666. return this._restPose;
  60667. };
  60668. Bone.prototype.returnToRest = function () {
  60669. this.updateMatrix(this._restPose.clone());
  60670. };
  60671. Bone.prototype.getWorldMatrix = function () {
  60672. return this._worldTransform;
  60673. };
  60674. Bone.prototype.getInvertedAbsoluteTransform = function () {
  60675. return this._invertedAbsoluteTransform;
  60676. };
  60677. Bone.prototype.getAbsoluteTransform = function () {
  60678. return this._absoluteTransform;
  60679. };
  60680. Object.defineProperty(Bone.prototype, "position", {
  60681. // Properties (matches AbstractMesh properties)
  60682. get: function () {
  60683. return this.getPosition();
  60684. },
  60685. set: function (newPosition) {
  60686. this.setPosition(newPosition);
  60687. },
  60688. enumerable: true,
  60689. configurable: true
  60690. });
  60691. Object.defineProperty(Bone.prototype, "rotation", {
  60692. get: function () {
  60693. return this.getRotation();
  60694. },
  60695. set: function (newRotation) {
  60696. this.setRotation(newRotation);
  60697. },
  60698. enumerable: true,
  60699. configurable: true
  60700. });
  60701. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  60702. get: function () {
  60703. return this.getRotationQuaternion();
  60704. },
  60705. set: function (newRotation) {
  60706. this.setRotationQuaternion(newRotation);
  60707. },
  60708. enumerable: true,
  60709. configurable: true
  60710. });
  60711. Object.defineProperty(Bone.prototype, "scaling", {
  60712. get: function () {
  60713. return this.getScale();
  60714. },
  60715. set: function (newScaling) {
  60716. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  60717. },
  60718. enumerable: true,
  60719. configurable: true
  60720. });
  60721. // Methods
  60722. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  60723. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  60724. this._baseMatrix = matrix.clone();
  60725. this._localMatrix = matrix.clone();
  60726. this._skeleton._markAsDirty();
  60727. if (updateDifferenceMatrix) {
  60728. this._updateDifferenceMatrix();
  60729. }
  60730. };
  60731. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  60732. if (!rootMatrix) {
  60733. rootMatrix = this._baseMatrix;
  60734. }
  60735. if (this._parent) {
  60736. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  60737. }
  60738. else {
  60739. this._absoluteTransform.copyFrom(rootMatrix);
  60740. }
  60741. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  60742. for (var index = 0; index < this.children.length; index++) {
  60743. this.children[index]._updateDifferenceMatrix();
  60744. }
  60745. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  60746. };
  60747. Bone.prototype.markAsDirty = function () {
  60748. this._currentRenderId++;
  60749. this._skeleton._markAsDirty();
  60750. };
  60751. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  60752. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  60753. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  60754. // all animation may be coming from a library skeleton, so may need to create animation
  60755. if (this.animations.length === 0) {
  60756. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  60757. this.animations[0].setKeys([]);
  60758. }
  60759. // get animation info / verify there is such a range from the source bone
  60760. var sourceRange = source.animations[0].getRange(rangeName);
  60761. if (!sourceRange) {
  60762. return false;
  60763. }
  60764. var from = sourceRange.from;
  60765. var to = sourceRange.to;
  60766. var sourceKeys = source.animations[0].getKeys();
  60767. // rescaling prep
  60768. var sourceBoneLength = source.length;
  60769. var sourceParent = source.getParent();
  60770. var parent = this.getParent();
  60771. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  60772. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  60773. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  60774. var destKeys = this.animations[0].getKeys();
  60775. // loop vars declaration
  60776. var orig;
  60777. var origTranslation;
  60778. var mat;
  60779. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  60780. orig = sourceKeys[key];
  60781. if (orig.frame >= from && orig.frame <= to) {
  60782. if (rescaleAsRequired) {
  60783. mat = orig.value.clone();
  60784. // scale based on parent ratio, when bone has parent
  60785. if (parentScalingReqd) {
  60786. origTranslation = mat.getTranslation();
  60787. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  60788. // scale based on skeleton dimension ratio when root bone, and value is passed
  60789. }
  60790. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  60791. origTranslation = mat.getTranslation();
  60792. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  60793. // use original when root bone, and no data for skelDimensionsRatio
  60794. }
  60795. else {
  60796. mat = orig.value;
  60797. }
  60798. }
  60799. else {
  60800. mat = orig.value;
  60801. }
  60802. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  60803. }
  60804. }
  60805. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  60806. return true;
  60807. };
  60808. /**
  60809. * Translate the bone in local or world space.
  60810. * @param vec The amount to translate the bone.
  60811. * @param space The space that the translation is in.
  60812. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60813. */
  60814. Bone.prototype.translate = function (vec, space, mesh) {
  60815. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60816. var lm = this.getLocalMatrix();
  60817. if (space == BABYLON.Space.LOCAL) {
  60818. lm.m[12] += vec.x;
  60819. lm.m[13] += vec.y;
  60820. lm.m[14] += vec.z;
  60821. }
  60822. else {
  60823. var wm = null;
  60824. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60825. if (mesh) {
  60826. wm = mesh.getWorldMatrix();
  60827. }
  60828. this._skeleton.computeAbsoluteTransforms();
  60829. var tmat = Bone._tmpMats[0];
  60830. var tvec = Bone._tmpVecs[0];
  60831. if (this._parent) {
  60832. if (mesh && wm) {
  60833. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60834. tmat.multiplyToRef(wm, tmat);
  60835. }
  60836. else {
  60837. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60838. }
  60839. }
  60840. tmat.m[12] = 0;
  60841. tmat.m[13] = 0;
  60842. tmat.m[14] = 0;
  60843. tmat.invert();
  60844. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  60845. lm.m[12] += tvec.x;
  60846. lm.m[13] += tvec.y;
  60847. lm.m[14] += tvec.z;
  60848. }
  60849. this.markAsDirty();
  60850. };
  60851. /**
  60852. * Set the postion of the bone in local or world space.
  60853. * @param position The position to set the bone.
  60854. * @param space The space that the position is in.
  60855. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60856. */
  60857. Bone.prototype.setPosition = function (position, space, mesh) {
  60858. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60859. var lm = this.getLocalMatrix();
  60860. if (space == BABYLON.Space.LOCAL) {
  60861. lm.m[12] = position.x;
  60862. lm.m[13] = position.y;
  60863. lm.m[14] = position.z;
  60864. }
  60865. else {
  60866. var wm = null;
  60867. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  60868. if (mesh) {
  60869. wm = mesh.getWorldMatrix();
  60870. }
  60871. this._skeleton.computeAbsoluteTransforms();
  60872. var tmat = Bone._tmpMats[0];
  60873. var vec = Bone._tmpVecs[0];
  60874. if (this._parent) {
  60875. if (mesh && wm) {
  60876. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60877. tmat.multiplyToRef(wm, tmat);
  60878. }
  60879. else {
  60880. tmat.copyFrom(this._parent.getAbsoluteTransform());
  60881. }
  60882. }
  60883. tmat.invert();
  60884. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  60885. lm.m[12] = vec.x;
  60886. lm.m[13] = vec.y;
  60887. lm.m[14] = vec.z;
  60888. }
  60889. this.markAsDirty();
  60890. };
  60891. /**
  60892. * Set the absolute postion of the bone (world space).
  60893. * @param position The position to set the bone.
  60894. * @param mesh The mesh that this bone is attached to.
  60895. */
  60896. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  60897. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  60898. };
  60899. /**
  60900. * Set the scale of the bone on the x, y and z axes.
  60901. * @param x The scale of the bone on the x axis.
  60902. * @param x The scale of the bone on the y axis.
  60903. * @param z The scale of the bone on the z axis.
  60904. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60905. */
  60906. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  60907. if (scaleChildren === void 0) { scaleChildren = false; }
  60908. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  60909. if (!scaleChildren) {
  60910. this._negateScaleChildren.x = 1 / x;
  60911. this._negateScaleChildren.y = 1 / y;
  60912. this._negateScaleChildren.z = 1 / z;
  60913. }
  60914. this._syncScaleVector();
  60915. }
  60916. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  60917. };
  60918. /**
  60919. * Scale the bone on the x, y and z axes.
  60920. * @param x The amount to scale the bone on the x axis.
  60921. * @param x The amount to scale the bone on the y axis.
  60922. * @param z The amount to scale the bone on the z axis.
  60923. * @param scaleChildren Set this to true if children of the bone should be scaled.
  60924. */
  60925. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  60926. if (scaleChildren === void 0) { scaleChildren = false; }
  60927. var locMat = this.getLocalMatrix();
  60928. var origLocMat = Bone._tmpMats[0];
  60929. origLocMat.copyFrom(locMat);
  60930. var origLocMatInv = Bone._tmpMats[1];
  60931. origLocMatInv.copyFrom(origLocMat);
  60932. origLocMatInv.invert();
  60933. var scaleMat = Bone._tmpMats[2];
  60934. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  60935. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  60936. this._scaleVector.x *= x;
  60937. this._scaleVector.y *= y;
  60938. this._scaleVector.z *= z;
  60939. locMat.multiplyToRef(origLocMatInv, locMat);
  60940. locMat.multiplyToRef(scaleMat, locMat);
  60941. locMat.multiplyToRef(origLocMat, locMat);
  60942. var parent = this.getParent();
  60943. if (parent) {
  60944. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  60945. }
  60946. else {
  60947. this.getAbsoluteTransform().copyFrom(locMat);
  60948. }
  60949. var len = this.children.length;
  60950. scaleMat.invert();
  60951. for (var i = 0; i < len; i++) {
  60952. var child = this.children[i];
  60953. var cm = child.getLocalMatrix();
  60954. cm.multiplyToRef(scaleMat, cm);
  60955. var lm = child.getLocalMatrix();
  60956. lm.m[12] *= x;
  60957. lm.m[13] *= y;
  60958. lm.m[14] *= z;
  60959. }
  60960. this.computeAbsoluteTransforms();
  60961. if (scaleChildren) {
  60962. for (var i = 0; i < len; i++) {
  60963. this.children[i].scale(x, y, z, scaleChildren);
  60964. }
  60965. }
  60966. this.markAsDirty();
  60967. };
  60968. /**
  60969. * Set the yaw, pitch, and roll of the bone in local or world space.
  60970. * @param yaw The rotation of the bone on the y axis.
  60971. * @param pitch The rotation of the bone on the x axis.
  60972. * @param roll The rotation of the bone on the z axis.
  60973. * @param space The space that the axes of rotation are in.
  60974. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60975. */
  60976. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  60977. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60978. var rotMat = Bone._tmpMats[0];
  60979. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  60980. var rotMatInv = Bone._tmpMats[1];
  60981. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  60982. rotMatInv.multiplyToRef(rotMat, rotMat);
  60983. this._rotateWithMatrix(rotMat, space, mesh);
  60984. };
  60985. /**
  60986. * Rotate the bone on an axis in local or world space.
  60987. * @param axis The axis to rotate the bone on.
  60988. * @param amount The amount to rotate the bone.
  60989. * @param space The space that the axis is in.
  60990. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  60991. */
  60992. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  60993. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  60994. var rmat = Bone._tmpMats[0];
  60995. rmat.m[12] = 0;
  60996. rmat.m[13] = 0;
  60997. rmat.m[14] = 0;
  60998. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  60999. this._rotateWithMatrix(rmat, space, mesh);
  61000. };
  61001. /**
  61002. * Set the rotation of the bone to a particular axis angle in local or world space.
  61003. * @param axis The axis to rotate the bone on.
  61004. * @param angle The angle that the bone should be rotated to.
  61005. * @param space The space that the axis is in.
  61006. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61007. */
  61008. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  61009. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61010. var rotMat = Bone._tmpMats[0];
  61011. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  61012. var rotMatInv = Bone._tmpMats[1];
  61013. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61014. rotMatInv.multiplyToRef(rotMat, rotMat);
  61015. this._rotateWithMatrix(rotMat, space, mesh);
  61016. };
  61017. /**
  61018. * Set the euler rotation of the bone in local of world space.
  61019. * @param rotation The euler rotation that the bone should be set to.
  61020. * @param space The space that the rotation is in.
  61021. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61022. */
  61023. Bone.prototype.setRotation = function (rotation, space, mesh) {
  61024. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61025. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  61026. };
  61027. /**
  61028. * Set the quaternion rotation of the bone in local of world space.
  61029. * @param quat The quaternion rotation that the bone should be set to.
  61030. * @param space The space that the rotation is in.
  61031. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61032. */
  61033. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  61034. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61035. var rotMatInv = Bone._tmpMats[0];
  61036. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61037. var rotMat = Bone._tmpMats[1];
  61038. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  61039. rotMatInv.multiplyToRef(rotMat, rotMat);
  61040. this._rotateWithMatrix(rotMat, space, mesh);
  61041. };
  61042. /**
  61043. * Set the rotation matrix of the bone in local of world space.
  61044. * @param rotMat The rotation matrix that the bone should be set to.
  61045. * @param space The space that the rotation is in.
  61046. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61047. */
  61048. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  61049. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61050. var rotMatInv = Bone._tmpMats[0];
  61051. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  61052. var rotMat2 = Bone._tmpMats[1];
  61053. rotMat2.copyFrom(rotMat);
  61054. rotMatInv.multiplyToRef(rotMat, rotMat2);
  61055. this._rotateWithMatrix(rotMat2, space, mesh);
  61056. };
  61057. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  61058. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61059. var lmat = this.getLocalMatrix();
  61060. var lx = lmat.m[12];
  61061. var ly = lmat.m[13];
  61062. var lz = lmat.m[14];
  61063. var parent = this.getParent();
  61064. var parentScale = Bone._tmpMats[3];
  61065. var parentScaleInv = Bone._tmpMats[4];
  61066. if (parent) {
  61067. if (space == BABYLON.Space.WORLD) {
  61068. if (mesh) {
  61069. parentScale.copyFrom(mesh.getWorldMatrix());
  61070. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  61071. }
  61072. else {
  61073. parentScale.copyFrom(parent.getAbsoluteTransform());
  61074. }
  61075. }
  61076. else {
  61077. parentScale = parent._scaleMatrix;
  61078. }
  61079. parentScaleInv.copyFrom(parentScale);
  61080. parentScaleInv.invert();
  61081. lmat.multiplyToRef(parentScale, lmat);
  61082. lmat.multiplyToRef(rmat, lmat);
  61083. lmat.multiplyToRef(parentScaleInv, lmat);
  61084. }
  61085. else {
  61086. if (space == BABYLON.Space.WORLD && mesh) {
  61087. parentScale.copyFrom(mesh.getWorldMatrix());
  61088. parentScaleInv.copyFrom(parentScale);
  61089. parentScaleInv.invert();
  61090. lmat.multiplyToRef(parentScale, lmat);
  61091. lmat.multiplyToRef(rmat, lmat);
  61092. lmat.multiplyToRef(parentScaleInv, lmat);
  61093. }
  61094. else {
  61095. lmat.multiplyToRef(rmat, lmat);
  61096. }
  61097. }
  61098. lmat.m[12] = lx;
  61099. lmat.m[13] = ly;
  61100. lmat.m[14] = lz;
  61101. this.computeAbsoluteTransforms();
  61102. this.markAsDirty();
  61103. };
  61104. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  61105. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61106. if (space == BABYLON.Space.WORLD) {
  61107. var scaleMatrix = Bone._tmpMats[2];
  61108. scaleMatrix.copyFrom(this._scaleMatrix);
  61109. rotMatInv.copyFrom(this.getAbsoluteTransform());
  61110. if (mesh) {
  61111. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  61112. var meshScale = Bone._tmpMats[3];
  61113. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  61114. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  61115. }
  61116. rotMatInv.invert();
  61117. scaleMatrix.m[0] *= this._scalingDeterminant;
  61118. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61119. }
  61120. else {
  61121. rotMatInv.copyFrom(this.getLocalMatrix());
  61122. rotMatInv.invert();
  61123. var scaleMatrix = Bone._tmpMats[2];
  61124. scaleMatrix.copyFrom(this._scaleMatrix);
  61125. if (this._parent) {
  61126. var pscaleMatrix = Bone._tmpMats[3];
  61127. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  61128. pscaleMatrix.invert();
  61129. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  61130. }
  61131. else {
  61132. scaleMatrix.m[0] *= this._scalingDeterminant;
  61133. }
  61134. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  61135. }
  61136. };
  61137. /**
  61138. * Get the scale of the bone
  61139. * @returns the scale of the bone
  61140. */
  61141. Bone.prototype.getScale = function () {
  61142. return this._scaleVector.clone();
  61143. };
  61144. /**
  61145. * Copy the scale of the bone to a vector3.
  61146. * @param result The vector3 to copy the scale to
  61147. */
  61148. Bone.prototype.getScaleToRef = function (result) {
  61149. result.copyFrom(this._scaleVector);
  61150. };
  61151. /**
  61152. * Get the position of the bone in local or world space.
  61153. * @param space The space that the returned position is in.
  61154. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61155. * @returns The position of the bone
  61156. */
  61157. Bone.prototype.getPosition = function (space, mesh) {
  61158. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61159. if (mesh === void 0) { mesh = null; }
  61160. var pos = BABYLON.Vector3.Zero();
  61161. this.getPositionToRef(space, mesh, pos);
  61162. return pos;
  61163. };
  61164. /**
  61165. * Copy the position of the bone to a vector3 in local or world space.
  61166. * @param space The space that the returned position is in.
  61167. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61168. * @param result The vector3 to copy the position to.
  61169. */
  61170. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  61171. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61172. if (space == BABYLON.Space.LOCAL) {
  61173. var lm = this.getLocalMatrix();
  61174. result.x = lm.m[12];
  61175. result.y = lm.m[13];
  61176. result.z = lm.m[14];
  61177. }
  61178. else {
  61179. var wm = null;
  61180. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61181. if (mesh) {
  61182. wm = mesh.getWorldMatrix();
  61183. }
  61184. this._skeleton.computeAbsoluteTransforms();
  61185. var tmat = Bone._tmpMats[0];
  61186. if (mesh && wm) {
  61187. tmat.copyFrom(this.getAbsoluteTransform());
  61188. tmat.multiplyToRef(wm, tmat);
  61189. }
  61190. else {
  61191. tmat = this.getAbsoluteTransform();
  61192. }
  61193. result.x = tmat.m[12];
  61194. result.y = tmat.m[13];
  61195. result.z = tmat.m[14];
  61196. }
  61197. };
  61198. /**
  61199. * Get the absolute position of the bone (world space).
  61200. * @param mesh The mesh that this bone is attached to.
  61201. * @returns The absolute position of the bone
  61202. */
  61203. Bone.prototype.getAbsolutePosition = function (mesh) {
  61204. if (mesh === void 0) { mesh = null; }
  61205. var pos = BABYLON.Vector3.Zero();
  61206. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  61207. return pos;
  61208. };
  61209. /**
  61210. * Copy the absolute position of the bone (world space) to the result param.
  61211. * @param mesh The mesh that this bone is attached to.
  61212. * @param result The vector3 to copy the absolute position to.
  61213. */
  61214. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  61215. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  61216. };
  61217. /**
  61218. * Compute the absolute transforms of this bone and its children.
  61219. */
  61220. Bone.prototype.computeAbsoluteTransforms = function () {
  61221. if (this._parent) {
  61222. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  61223. }
  61224. else {
  61225. this._absoluteTransform.copyFrom(this._localMatrix);
  61226. var poseMatrix = this._skeleton.getPoseMatrix();
  61227. if (poseMatrix) {
  61228. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  61229. }
  61230. }
  61231. var children = this.children;
  61232. var len = children.length;
  61233. for (var i = 0; i < len; i++) {
  61234. children[i].computeAbsoluteTransforms();
  61235. }
  61236. };
  61237. Bone.prototype._syncScaleVector = function () {
  61238. var lm = this.getLocalMatrix();
  61239. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  61240. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  61241. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  61242. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  61243. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  61244. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  61245. this._scaleVector.x = xs * Math.sqrt(xsq);
  61246. this._scaleVector.y = ys * Math.sqrt(ysq);
  61247. this._scaleVector.z = zs * Math.sqrt(zsq);
  61248. if (this._parent) {
  61249. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  61250. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  61251. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  61252. }
  61253. 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);
  61254. };
  61255. /**
  61256. * Get the world direction from an axis that is in the local space of the bone.
  61257. * @param localAxis The local direction that is used to compute the world direction.
  61258. * @param mesh The mesh that this bone is attached to.
  61259. * @returns The world direction
  61260. */
  61261. Bone.prototype.getDirection = function (localAxis, mesh) {
  61262. if (mesh === void 0) { mesh = null; }
  61263. var result = BABYLON.Vector3.Zero();
  61264. this.getDirectionToRef(localAxis, mesh, result);
  61265. return result;
  61266. };
  61267. /**
  61268. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  61269. * @param localAxis The local direction that is used to compute the world direction.
  61270. * @param mesh The mesh that this bone is attached to.
  61271. * @param result The vector3 that the world direction will be copied to.
  61272. */
  61273. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  61274. if (mesh === void 0) { mesh = null; }
  61275. var wm = null;
  61276. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61277. if (mesh) {
  61278. wm = mesh.getWorldMatrix();
  61279. }
  61280. this._skeleton.computeAbsoluteTransforms();
  61281. var mat = Bone._tmpMats[0];
  61282. mat.copyFrom(this.getAbsoluteTransform());
  61283. if (mesh && wm) {
  61284. mat.multiplyToRef(wm, mat);
  61285. }
  61286. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  61287. result.normalize();
  61288. };
  61289. /**
  61290. * Get the euler rotation of the bone in local or world space.
  61291. * @param space The space that the rotation should be in.
  61292. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61293. * @returns The euler rotation
  61294. */
  61295. Bone.prototype.getRotation = function (space, mesh) {
  61296. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61297. if (mesh === void 0) { mesh = null; }
  61298. var result = BABYLON.Vector3.Zero();
  61299. this.getRotationToRef(space, mesh, result);
  61300. return result;
  61301. };
  61302. /**
  61303. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  61304. * @param space The space that the rotation should be in.
  61305. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61306. * @param result The vector3 that the rotation should be copied to.
  61307. */
  61308. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  61309. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61310. if (mesh === void 0) { mesh = null; }
  61311. var quat = Bone._tmpQuat;
  61312. this.getRotationQuaternionToRef(space, mesh, quat);
  61313. quat.toEulerAnglesToRef(result);
  61314. };
  61315. /**
  61316. * Get the quaternion rotation of the bone in either local or world space.
  61317. * @param space The space that the rotation should be in.
  61318. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61319. * @returns The quaternion rotation
  61320. */
  61321. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  61322. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61323. if (mesh === void 0) { mesh = null; }
  61324. var result = BABYLON.Quaternion.Identity();
  61325. this.getRotationQuaternionToRef(space, mesh, result);
  61326. return result;
  61327. };
  61328. /**
  61329. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  61330. * @param space The space that the rotation should be in.
  61331. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61332. * @param result The quaternion that the rotation should be copied to.
  61333. */
  61334. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  61335. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61336. if (mesh === void 0) { mesh = null; }
  61337. if (space == BABYLON.Space.LOCAL) {
  61338. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61339. }
  61340. else {
  61341. var mat = Bone._tmpMats[0];
  61342. var amat = this.getAbsoluteTransform();
  61343. if (mesh) {
  61344. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61345. }
  61346. else {
  61347. mat.copyFrom(amat);
  61348. }
  61349. mat.m[0] *= this._scalingDeterminant;
  61350. mat.m[1] *= this._scalingDeterminant;
  61351. mat.m[2] *= this._scalingDeterminant;
  61352. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  61353. }
  61354. };
  61355. /**
  61356. * Get the rotation matrix of the bone in local or world space.
  61357. * @param space The space that the rotation should be in.
  61358. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61359. * @returns The rotation matrix
  61360. */
  61361. Bone.prototype.getRotationMatrix = function (space, mesh) {
  61362. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61363. var result = BABYLON.Matrix.Identity();
  61364. this.getRotationMatrixToRef(space, mesh, result);
  61365. return result;
  61366. };
  61367. /**
  61368. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  61369. * @param space The space that the rotation should be in.
  61370. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  61371. * @param result The quaternion that the rotation should be copied to.
  61372. */
  61373. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  61374. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  61375. if (space == BABYLON.Space.LOCAL) {
  61376. this.getLocalMatrix().getRotationMatrixToRef(result);
  61377. }
  61378. else {
  61379. var mat = Bone._tmpMats[0];
  61380. var amat = this.getAbsoluteTransform();
  61381. if (mesh) {
  61382. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  61383. }
  61384. else {
  61385. mat.copyFrom(amat);
  61386. }
  61387. mat.m[0] *= this._scalingDeterminant;
  61388. mat.m[1] *= this._scalingDeterminant;
  61389. mat.m[2] *= this._scalingDeterminant;
  61390. mat.getRotationMatrixToRef(result);
  61391. }
  61392. };
  61393. /**
  61394. * Get the world position of a point that is in the local space of the bone.
  61395. * @param position The local position
  61396. * @param mesh The mesh that this bone is attached to.
  61397. * @returns The world position
  61398. */
  61399. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  61400. if (mesh === void 0) { mesh = null; }
  61401. var result = BABYLON.Vector3.Zero();
  61402. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  61403. return result;
  61404. };
  61405. /**
  61406. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  61407. * @param position The local position
  61408. * @param mesh The mesh that this bone is attached to.
  61409. * @param result The vector3 that the world position should be copied to.
  61410. */
  61411. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  61412. if (mesh === void 0) { mesh = null; }
  61413. var wm = null;
  61414. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61415. if (mesh) {
  61416. wm = mesh.getWorldMatrix();
  61417. }
  61418. this._skeleton.computeAbsoluteTransforms();
  61419. var tmat = Bone._tmpMats[0];
  61420. if (mesh && wm) {
  61421. tmat.copyFrom(this.getAbsoluteTransform());
  61422. tmat.multiplyToRef(wm, tmat);
  61423. }
  61424. else {
  61425. tmat = this.getAbsoluteTransform();
  61426. }
  61427. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61428. };
  61429. /**
  61430. * Get the local position of a point that is in world space.
  61431. * @param position The world position
  61432. * @param mesh The mesh that this bone is attached to.
  61433. * @returns The local position
  61434. */
  61435. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  61436. if (mesh === void 0) { mesh = null; }
  61437. var result = BABYLON.Vector3.Zero();
  61438. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  61439. return result;
  61440. };
  61441. /**
  61442. * Get the local position of a point that is in world space and copy it to the result param.
  61443. * @param position The world position
  61444. * @param mesh The mesh that this bone is attached to.
  61445. * @param result The vector3 that the local position should be copied to.
  61446. */
  61447. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  61448. if (mesh === void 0) { mesh = null; }
  61449. var wm = null;
  61450. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  61451. if (mesh) {
  61452. wm = mesh.getWorldMatrix();
  61453. }
  61454. this._skeleton.computeAbsoluteTransforms();
  61455. var tmat = Bone._tmpMats[0];
  61456. tmat.copyFrom(this.getAbsoluteTransform());
  61457. if (mesh && wm) {
  61458. tmat.multiplyToRef(wm, tmat);
  61459. }
  61460. tmat.invert();
  61461. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  61462. };
  61463. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61464. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  61465. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61466. return Bone;
  61467. }(BABYLON.Node));
  61468. BABYLON.Bone = Bone;
  61469. })(BABYLON || (BABYLON = {}));
  61470. //# sourceMappingURL=babylon.bone.js.map
  61471. var BABYLON;
  61472. (function (BABYLON) {
  61473. var BoneIKController = /** @class */ (function () {
  61474. function BoneIKController(mesh, bone, options) {
  61475. this.targetPosition = BABYLON.Vector3.Zero();
  61476. this.poleTargetPosition = BABYLON.Vector3.Zero();
  61477. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  61478. this.poleAngle = 0;
  61479. this.slerpAmount = 1;
  61480. this._bone1Quat = BABYLON.Quaternion.Identity();
  61481. this._bone1Mat = BABYLON.Matrix.Identity();
  61482. this._bone2Ang = Math.PI;
  61483. this._maxAngle = Math.PI;
  61484. this._rightHandedSystem = false;
  61485. this._bendAxis = BABYLON.Vector3.Right();
  61486. this._slerping = false;
  61487. this._adjustRoll = 0;
  61488. this._bone2 = bone;
  61489. this._bone1 = bone.getParent();
  61490. if (!this._bone1) {
  61491. return;
  61492. }
  61493. this.mesh = mesh;
  61494. var bonePos = bone.getPosition();
  61495. if (bone.getAbsoluteTransform().determinant() > 0) {
  61496. this._rightHandedSystem = true;
  61497. this._bendAxis.x = 0;
  61498. this._bendAxis.y = 0;
  61499. this._bendAxis.z = -1;
  61500. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  61501. this._adjustRoll = Math.PI * .5;
  61502. this._bendAxis.z = 1;
  61503. }
  61504. }
  61505. if (this._bone1.length) {
  61506. var boneScale1 = this._bone1.getScale();
  61507. var boneScale2 = this._bone2.getScale();
  61508. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  61509. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  61510. }
  61511. else if (this._bone1.children[0]) {
  61512. mesh.computeWorldMatrix(true);
  61513. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  61514. var pos2 = this._bone2.getAbsolutePosition(mesh);
  61515. var pos3 = this._bone1.getAbsolutePosition(mesh);
  61516. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  61517. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  61518. }
  61519. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  61520. this.maxAngle = Math.PI;
  61521. if (options) {
  61522. if (options.targetMesh) {
  61523. this.targetMesh = options.targetMesh;
  61524. this.targetMesh.computeWorldMatrix(true);
  61525. }
  61526. if (options.poleTargetMesh) {
  61527. this.poleTargetMesh = options.poleTargetMesh;
  61528. this.poleTargetMesh.computeWorldMatrix(true);
  61529. }
  61530. else if (options.poleTargetBone) {
  61531. this.poleTargetBone = options.poleTargetBone;
  61532. }
  61533. else if (this._bone1.getParent()) {
  61534. this.poleTargetBone = this._bone1.getParent();
  61535. }
  61536. if (options.poleTargetLocalOffset) {
  61537. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  61538. }
  61539. if (options.poleAngle) {
  61540. this.poleAngle = options.poleAngle;
  61541. }
  61542. if (options.bendAxis) {
  61543. this._bendAxis.copyFrom(options.bendAxis);
  61544. }
  61545. if (options.maxAngle) {
  61546. this.maxAngle = options.maxAngle;
  61547. }
  61548. if (options.slerpAmount) {
  61549. this.slerpAmount = options.slerpAmount;
  61550. }
  61551. }
  61552. }
  61553. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  61554. get: function () {
  61555. return this._maxAngle;
  61556. },
  61557. set: function (value) {
  61558. this._setMaxAngle(value);
  61559. },
  61560. enumerable: true,
  61561. configurable: true
  61562. });
  61563. BoneIKController.prototype._setMaxAngle = function (ang) {
  61564. if (ang < 0) {
  61565. ang = 0;
  61566. }
  61567. if (ang > Math.PI || ang == undefined) {
  61568. ang = Math.PI;
  61569. }
  61570. this._maxAngle = ang;
  61571. var a = this._bone1Length;
  61572. var b = this._bone2Length;
  61573. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  61574. };
  61575. BoneIKController.prototype.update = function () {
  61576. var bone1 = this._bone1;
  61577. if (!bone1) {
  61578. return;
  61579. }
  61580. var target = this.targetPosition;
  61581. var poleTarget = this.poleTargetPosition;
  61582. var mat1 = BoneIKController._tmpMats[0];
  61583. var mat2 = BoneIKController._tmpMats[1];
  61584. if (this.targetMesh) {
  61585. target.copyFrom(this.targetMesh.getAbsolutePosition());
  61586. }
  61587. if (this.poleTargetBone) {
  61588. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  61589. }
  61590. else if (this.poleTargetMesh) {
  61591. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  61592. }
  61593. var bonePos = BoneIKController._tmpVecs[0];
  61594. var zaxis = BoneIKController._tmpVecs[1];
  61595. var xaxis = BoneIKController._tmpVecs[2];
  61596. var yaxis = BoneIKController._tmpVecs[3];
  61597. var upAxis = BoneIKController._tmpVecs[4];
  61598. var _tmpQuat = BoneIKController._tmpQuat;
  61599. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  61600. poleTarget.subtractToRef(bonePos, upAxis);
  61601. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  61602. upAxis.y = 1;
  61603. }
  61604. else {
  61605. upAxis.normalize();
  61606. }
  61607. target.subtractToRef(bonePos, yaxis);
  61608. yaxis.normalize();
  61609. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  61610. zaxis.normalize();
  61611. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  61612. xaxis.normalize();
  61613. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  61614. var a = this._bone1Length;
  61615. var b = this._bone2Length;
  61616. var c = BABYLON.Vector3.Distance(bonePos, target);
  61617. if (this._maxReach > 0) {
  61618. c = Math.min(this._maxReach, c);
  61619. }
  61620. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  61621. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  61622. if (acosa > 1) {
  61623. acosa = 1;
  61624. }
  61625. if (acosb > 1) {
  61626. acosb = 1;
  61627. }
  61628. if (acosa < -1) {
  61629. acosa = -1;
  61630. }
  61631. if (acosb < -1) {
  61632. acosb = -1;
  61633. }
  61634. var angA = Math.acos(acosa);
  61635. var angB = Math.acos(acosb);
  61636. var angC = -angA - angB;
  61637. if (this._rightHandedSystem) {
  61638. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  61639. mat2.multiplyToRef(mat1, mat1);
  61640. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  61641. mat2.multiplyToRef(mat1, mat1);
  61642. }
  61643. else {
  61644. var _tmpVec = BoneIKController._tmpVecs[5];
  61645. _tmpVec.copyFrom(this._bendAxis);
  61646. _tmpVec.x *= -1;
  61647. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  61648. mat2.multiplyToRef(mat1, mat1);
  61649. }
  61650. if (this.poleAngle) {
  61651. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  61652. mat1.multiplyToRef(mat2, mat1);
  61653. }
  61654. if (this._bone1) {
  61655. if (this.slerpAmount < 1) {
  61656. if (!this._slerping) {
  61657. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  61658. }
  61659. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  61660. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  61661. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  61662. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  61663. this._slerping = true;
  61664. }
  61665. else {
  61666. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  61667. this._bone1Mat.copyFrom(mat1);
  61668. this._slerping = false;
  61669. }
  61670. }
  61671. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  61672. this._bone2Ang = angC;
  61673. };
  61674. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  61675. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  61676. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  61677. return BoneIKController;
  61678. }());
  61679. BABYLON.BoneIKController = BoneIKController;
  61680. })(BABYLON || (BABYLON = {}));
  61681. //# sourceMappingURL=babylon.boneIKController.js.map
  61682. var BABYLON;
  61683. (function (BABYLON) {
  61684. var BoneLookController = /** @class */ (function () {
  61685. /**
  61686. * Create a BoneLookController
  61687. * @param mesh the mesh that the bone belongs to
  61688. * @param bone the bone that will be looking to the target
  61689. * @param target the target Vector3 to look at
  61690. * @param settings optional settings:
  61691. * - maxYaw: the maximum angle the bone will yaw to
  61692. * - minYaw: the minimum angle the bone will yaw to
  61693. * - maxPitch: the maximum angle the bone will pitch to
  61694. * - minPitch: the minimum angle the bone will yaw to
  61695. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  61696. * - upAxis: the up axis of the coordinate system
  61697. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61698. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  61699. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  61700. * - adjustYaw: used to make an adjustment to the yaw of the bone
  61701. * - adjustPitch: used to make an adjustment to the pitch of the bone
  61702. * - adjustRoll: used to make an adjustment to the roll of the bone
  61703. **/
  61704. function BoneLookController(mesh, bone, target, options) {
  61705. /**
  61706. * The up axis of the coordinate system that is used when the bone is rotated.
  61707. */
  61708. this.upAxis = BABYLON.Vector3.Up();
  61709. /**
  61710. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  61711. */
  61712. this.upAxisSpace = BABYLON.Space.LOCAL;
  61713. /**
  61714. * Used to make an adjustment to the yaw of the bone.
  61715. */
  61716. this.adjustYaw = 0;
  61717. /**
  61718. * Used to make an adjustment to the pitch of the bone.
  61719. */
  61720. this.adjustPitch = 0;
  61721. /**
  61722. * Used to make an adjustment to the roll of the bone.
  61723. */
  61724. this.adjustRoll = 0;
  61725. /**
  61726. * 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).
  61727. */
  61728. this.slerpAmount = 1;
  61729. this._boneQuat = BABYLON.Quaternion.Identity();
  61730. this._slerping = false;
  61731. this._firstFrameSkipped = false;
  61732. this._fowardAxis = BABYLON.Vector3.Forward();
  61733. this.mesh = mesh;
  61734. this.bone = bone;
  61735. this.target = target;
  61736. if (options) {
  61737. if (options.adjustYaw) {
  61738. this.adjustYaw = options.adjustYaw;
  61739. }
  61740. if (options.adjustPitch) {
  61741. this.adjustPitch = options.adjustPitch;
  61742. }
  61743. if (options.adjustRoll) {
  61744. this.adjustRoll = options.adjustRoll;
  61745. }
  61746. if (options.maxYaw != null) {
  61747. this.maxYaw = options.maxYaw;
  61748. }
  61749. else {
  61750. this.maxYaw = Math.PI;
  61751. }
  61752. if (options.minYaw != null) {
  61753. this.minYaw = options.minYaw;
  61754. }
  61755. else {
  61756. this.minYaw = -Math.PI;
  61757. }
  61758. if (options.maxPitch != null) {
  61759. this.maxPitch = options.maxPitch;
  61760. }
  61761. else {
  61762. this.maxPitch = Math.PI;
  61763. }
  61764. if (options.minPitch != null) {
  61765. this.minPitch = options.minPitch;
  61766. }
  61767. else {
  61768. this.minPitch = -Math.PI;
  61769. }
  61770. if (options.slerpAmount != null) {
  61771. this.slerpAmount = options.slerpAmount;
  61772. }
  61773. if (options.upAxis != null) {
  61774. this.upAxis = options.upAxis;
  61775. }
  61776. if (options.upAxisSpace != null) {
  61777. this.upAxisSpace = options.upAxisSpace;
  61778. }
  61779. if (options.yawAxis != null || options.pitchAxis != null) {
  61780. var newYawAxis = BABYLON.Axis.Y;
  61781. var newPitchAxis = BABYLON.Axis.X;
  61782. if (options.yawAxis != null) {
  61783. newYawAxis = options.yawAxis.clone();
  61784. newYawAxis.normalize();
  61785. }
  61786. if (options.pitchAxis != null) {
  61787. newPitchAxis = options.pitchAxis.clone();
  61788. newPitchAxis.normalize();
  61789. }
  61790. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  61791. this._transformYawPitch = BABYLON.Matrix.Identity();
  61792. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  61793. this._transformYawPitchInv = this._transformYawPitch.clone();
  61794. this._transformYawPitch.invert();
  61795. }
  61796. }
  61797. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  61798. this.upAxisSpace = BABYLON.Space.LOCAL;
  61799. }
  61800. }
  61801. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  61802. /**
  61803. * Get/set the minimum yaw angle that the bone can look to.
  61804. */
  61805. get: function () {
  61806. return this._minYaw;
  61807. },
  61808. set: function (value) {
  61809. this._minYaw = value;
  61810. this._minYawSin = Math.sin(value);
  61811. this._minYawCos = Math.cos(value);
  61812. if (this._maxYaw != null) {
  61813. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61814. this._yawRange = this._maxYaw - this._minYaw;
  61815. }
  61816. },
  61817. enumerable: true,
  61818. configurable: true
  61819. });
  61820. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  61821. /**
  61822. * Get/set the maximum yaw angle that the bone can look to.
  61823. */
  61824. get: function () {
  61825. return this._maxYaw;
  61826. },
  61827. set: function (value) {
  61828. this._maxYaw = value;
  61829. this._maxYawSin = Math.sin(value);
  61830. this._maxYawCos = Math.cos(value);
  61831. if (this._minYaw != null) {
  61832. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  61833. this._yawRange = this._maxYaw - this._minYaw;
  61834. }
  61835. },
  61836. enumerable: true,
  61837. configurable: true
  61838. });
  61839. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  61840. /**
  61841. * Get/set the minimum pitch angle that the bone can look to.
  61842. */
  61843. get: function () {
  61844. return this._minPitch;
  61845. },
  61846. set: function (value) {
  61847. this._minPitch = value;
  61848. this._minPitchTan = Math.tan(value);
  61849. },
  61850. enumerable: true,
  61851. configurable: true
  61852. });
  61853. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  61854. /**
  61855. * Get/set the maximum pitch angle that the bone can look to.
  61856. */
  61857. get: function () {
  61858. return this._maxPitch;
  61859. },
  61860. set: function (value) {
  61861. this._maxPitch = value;
  61862. this._maxPitchTan = Math.tan(value);
  61863. },
  61864. enumerable: true,
  61865. configurable: true
  61866. });
  61867. /**
  61868. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  61869. */
  61870. BoneLookController.prototype.update = function () {
  61871. //skip the first frame when slerping so that the mesh rotation is correct
  61872. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  61873. this._firstFrameSkipped = true;
  61874. return;
  61875. }
  61876. var bone = this.bone;
  61877. var bonePos = BoneLookController._tmpVecs[0];
  61878. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  61879. var target = this.target;
  61880. var _tmpMat1 = BoneLookController._tmpMats[0];
  61881. var _tmpMat2 = BoneLookController._tmpMats[1];
  61882. var mesh = this.mesh;
  61883. var parentBone = bone.getParent();
  61884. var upAxis = BoneLookController._tmpVecs[1];
  61885. upAxis.copyFrom(this.upAxis);
  61886. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  61887. if (this._transformYawPitch) {
  61888. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  61889. }
  61890. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  61891. }
  61892. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  61893. mesh.getDirectionToRef(upAxis, upAxis);
  61894. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  61895. upAxis.normalize();
  61896. }
  61897. }
  61898. var checkYaw = false;
  61899. var checkPitch = false;
  61900. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  61901. checkYaw = true;
  61902. }
  61903. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  61904. checkPitch = true;
  61905. }
  61906. if (checkYaw || checkPitch) {
  61907. var spaceMat = BoneLookController._tmpMats[2];
  61908. var spaceMatInv = BoneLookController._tmpMats[3];
  61909. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  61910. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  61911. }
  61912. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  61913. spaceMat.copyFrom(mesh.getWorldMatrix());
  61914. }
  61915. else {
  61916. var forwardAxis = BoneLookController._tmpVecs[2];
  61917. forwardAxis.copyFrom(this._fowardAxis);
  61918. if (this._transformYawPitch) {
  61919. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  61920. }
  61921. if (parentBone) {
  61922. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  61923. }
  61924. else {
  61925. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  61926. }
  61927. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  61928. rightAxis.normalize();
  61929. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  61930. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  61931. }
  61932. spaceMat.invertToRef(spaceMatInv);
  61933. var xzlen = null;
  61934. if (checkPitch) {
  61935. var localTarget = BoneLookController._tmpVecs[3];
  61936. target.subtractToRef(bonePos, localTarget);
  61937. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61938. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61939. var pitch = Math.atan2(localTarget.y, xzlen);
  61940. var newPitch = pitch;
  61941. if (pitch > this._maxPitch) {
  61942. localTarget.y = this._maxPitchTan * xzlen;
  61943. newPitch = this._maxPitch;
  61944. }
  61945. else if (pitch < this._minPitch) {
  61946. localTarget.y = this._minPitchTan * xzlen;
  61947. newPitch = this._minPitch;
  61948. }
  61949. if (pitch != newPitch) {
  61950. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  61951. localTarget.addInPlace(bonePos);
  61952. target = localTarget;
  61953. }
  61954. }
  61955. if (checkYaw) {
  61956. var localTarget = BoneLookController._tmpVecs[4];
  61957. target.subtractToRef(bonePos, localTarget);
  61958. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  61959. var yaw = Math.atan2(localTarget.x, localTarget.z);
  61960. var newYaw = yaw;
  61961. if (yaw > this._maxYaw || yaw < this._minYaw) {
  61962. if (xzlen == null) {
  61963. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  61964. }
  61965. if (this._yawRange > Math.PI) {
  61966. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  61967. localTarget.z = this._maxYawCos * xzlen;
  61968. localTarget.x = this._maxYawSin * xzlen;
  61969. newYaw = this._maxYaw;
  61970. }
  61971. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  61972. localTarget.z = this._minYawCos * xzlen;
  61973. localTarget.x = this._minYawSin * xzlen;
  61974. newYaw = this._minYaw;
  61975. }
  61976. }
  61977. else {
  61978. if (yaw > this._maxYaw) {
  61979. localTarget.z = this._maxYawCos * xzlen;
  61980. localTarget.x = this._maxYawSin * xzlen;
  61981. newYaw = this._maxYaw;
  61982. }
  61983. else if (yaw < this._minYaw) {
  61984. localTarget.z = this._minYawCos * xzlen;
  61985. localTarget.x = this._minYawSin * xzlen;
  61986. newYaw = this._minYaw;
  61987. }
  61988. }
  61989. }
  61990. if (this._slerping && this._yawRange > Math.PI) {
  61991. //are we going to be crossing into the min/max region?
  61992. var boneFwd = BoneLookController._tmpVecs[8];
  61993. boneFwd.copyFrom(BABYLON.Axis.Z);
  61994. if (this._transformYawPitch) {
  61995. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  61996. }
  61997. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  61998. this._boneQuat.toRotationMatrix(boneRotMat);
  61999. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  62000. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  62001. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  62002. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  62003. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  62004. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  62005. if (angBtwTar > angBtwMidYaw) {
  62006. if (xzlen == null) {
  62007. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  62008. }
  62009. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  62010. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  62011. if (angBtwMin < angBtwMax) {
  62012. newYaw = boneYaw + Math.PI * .75;
  62013. localTarget.z = Math.cos(newYaw) * xzlen;
  62014. localTarget.x = Math.sin(newYaw) * xzlen;
  62015. }
  62016. else {
  62017. newYaw = boneYaw - Math.PI * .75;
  62018. localTarget.z = Math.cos(newYaw) * xzlen;
  62019. localTarget.x = Math.sin(newYaw) * xzlen;
  62020. }
  62021. }
  62022. }
  62023. if (yaw != newYaw) {
  62024. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  62025. localTarget.addInPlace(bonePos);
  62026. target = localTarget;
  62027. }
  62028. }
  62029. }
  62030. var zaxis = BoneLookController._tmpVecs[5];
  62031. var xaxis = BoneLookController._tmpVecs[6];
  62032. var yaxis = BoneLookController._tmpVecs[7];
  62033. var _tmpQuat = BoneLookController._tmpQuat;
  62034. target.subtractToRef(bonePos, zaxis);
  62035. zaxis.normalize();
  62036. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  62037. xaxis.normalize();
  62038. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  62039. yaxis.normalize();
  62040. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  62041. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  62042. return;
  62043. }
  62044. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  62045. return;
  62046. }
  62047. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  62048. return;
  62049. }
  62050. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  62051. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  62052. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  62053. }
  62054. if (this.slerpAmount < 1) {
  62055. if (!this._slerping) {
  62056. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  62057. }
  62058. if (this._transformYawPitch) {
  62059. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62060. }
  62061. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  62062. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  62063. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  62064. this._slerping = true;
  62065. }
  62066. else {
  62067. if (this._transformYawPitch) {
  62068. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  62069. }
  62070. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  62071. this._slerping = false;
  62072. }
  62073. };
  62074. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  62075. var angDiff = ang2 - ang1;
  62076. angDiff %= Math.PI * 2;
  62077. if (angDiff > Math.PI) {
  62078. angDiff -= Math.PI * 2;
  62079. }
  62080. else if (angDiff < -Math.PI) {
  62081. angDiff += Math.PI * 2;
  62082. }
  62083. return angDiff;
  62084. };
  62085. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  62086. ang1 %= (2 * Math.PI);
  62087. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62088. ang2 %= (2 * Math.PI);
  62089. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62090. var ab = 0;
  62091. if (ang1 < ang2) {
  62092. ab = ang2 - ang1;
  62093. }
  62094. else {
  62095. ab = ang1 - ang2;
  62096. }
  62097. if (ab > Math.PI) {
  62098. ab = Math.PI * 2 - ab;
  62099. }
  62100. return ab;
  62101. };
  62102. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  62103. ang %= (2 * Math.PI);
  62104. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  62105. ang1 %= (2 * Math.PI);
  62106. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  62107. ang2 %= (2 * Math.PI);
  62108. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  62109. if (ang1 < ang2) {
  62110. if (ang > ang1 && ang < ang2) {
  62111. return true;
  62112. }
  62113. }
  62114. else {
  62115. if (ang > ang2 && ang < ang1) {
  62116. return true;
  62117. }
  62118. }
  62119. return false;
  62120. };
  62121. 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()];
  62122. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  62123. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  62124. return BoneLookController;
  62125. }());
  62126. BABYLON.BoneLookController = BoneLookController;
  62127. })(BABYLON || (BABYLON = {}));
  62128. //# sourceMappingURL=babylon.boneLookController.js.map
  62129. var BABYLON;
  62130. (function (BABYLON) {
  62131. var Skeleton = /** @class */ (function () {
  62132. function Skeleton(name, id, scene) {
  62133. this.name = name;
  62134. this.id = id;
  62135. this.bones = new Array();
  62136. this.needInitialSkinMatrix = false;
  62137. this._isDirty = true;
  62138. this._meshesWithPoseMatrix = new Array();
  62139. this._identity = BABYLON.Matrix.Identity();
  62140. this._ranges = {};
  62141. this._lastAbsoluteTransformsUpdateId = -1;
  62142. // Events
  62143. /**
  62144. * An event triggered before computing the skeleton's matrices
  62145. * @type {BABYLON.Observable}
  62146. */
  62147. this.onBeforeComputeObservable = new BABYLON.Observable();
  62148. this.bones = [];
  62149. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62150. scene.skeletons.push(this);
  62151. //make sure it will recalculate the matrix next time prepare is called.
  62152. this._isDirty = true;
  62153. }
  62154. // Members
  62155. Skeleton.prototype.getTransformMatrices = function (mesh) {
  62156. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  62157. return mesh._bonesTransformMatrices;
  62158. }
  62159. if (!this._transformMatrices) {
  62160. this.prepare();
  62161. }
  62162. return this._transformMatrices;
  62163. };
  62164. Skeleton.prototype.getScene = function () {
  62165. return this._scene;
  62166. };
  62167. // Methods
  62168. /**
  62169. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  62170. */
  62171. Skeleton.prototype.toString = function (fullDetails) {
  62172. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  62173. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  62174. if (fullDetails) {
  62175. ret += ", Ranges: {";
  62176. var first = true;
  62177. for (var name_1 in this._ranges) {
  62178. if (first) {
  62179. ret += ", ";
  62180. first = false;
  62181. }
  62182. ret += name_1;
  62183. }
  62184. ret += "}";
  62185. }
  62186. return ret;
  62187. };
  62188. /**
  62189. * Get bone's index searching by name
  62190. * @param {string} name is bone's name to search for
  62191. * @return {number} Indice of the bone. Returns -1 if not found
  62192. */
  62193. Skeleton.prototype.getBoneIndexByName = function (name) {
  62194. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  62195. if (this.bones[boneIndex].name === name) {
  62196. return boneIndex;
  62197. }
  62198. }
  62199. return -1;
  62200. };
  62201. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  62202. // check name not already in use
  62203. if (!this._ranges[name]) {
  62204. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  62205. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62206. if (this.bones[i].animations[0]) {
  62207. this.bones[i].animations[0].createRange(name, from, to);
  62208. }
  62209. }
  62210. }
  62211. };
  62212. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  62213. if (deleteFrames === void 0) { deleteFrames = true; }
  62214. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62215. if (this.bones[i].animations[0]) {
  62216. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  62217. }
  62218. }
  62219. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  62220. };
  62221. Skeleton.prototype.getAnimationRange = function (name) {
  62222. return this._ranges[name];
  62223. };
  62224. /**
  62225. * Returns as an Array, all AnimationRanges defined on this skeleton
  62226. */
  62227. Skeleton.prototype.getAnimationRanges = function () {
  62228. var animationRanges = [];
  62229. var name;
  62230. var i = 0;
  62231. for (name in this._ranges) {
  62232. animationRanges[i] = this._ranges[name];
  62233. i++;
  62234. }
  62235. return animationRanges;
  62236. };
  62237. /**
  62238. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  62239. */
  62240. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  62241. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  62242. if (this._ranges[name] || !source.getAnimationRange(name)) {
  62243. return false;
  62244. }
  62245. var ret = true;
  62246. var frameOffset = this._getHighestAnimationFrame() + 1;
  62247. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  62248. var boneDict = {};
  62249. var sourceBones = source.bones;
  62250. var nBones;
  62251. var i;
  62252. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  62253. boneDict[sourceBones[i].name] = sourceBones[i];
  62254. }
  62255. if (this.bones.length !== sourceBones.length) {
  62256. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  62257. ret = false;
  62258. }
  62259. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  62260. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  62261. var boneName = this.bones[i].name;
  62262. var sourceBone = boneDict[boneName];
  62263. if (sourceBone) {
  62264. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  62265. }
  62266. else {
  62267. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  62268. ret = false;
  62269. }
  62270. }
  62271. // do not call createAnimationRange(), since it also is done to bones, which was already done
  62272. var range = source.getAnimationRange(name);
  62273. if (range) {
  62274. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  62275. }
  62276. return ret;
  62277. };
  62278. Skeleton.prototype.returnToRest = function () {
  62279. for (var index = 0; index < this.bones.length; index++) {
  62280. this.bones[index].returnToRest();
  62281. }
  62282. };
  62283. Skeleton.prototype._getHighestAnimationFrame = function () {
  62284. var ret = 0;
  62285. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  62286. if (this.bones[i].animations[0]) {
  62287. var highest = this.bones[i].animations[0].getHighestFrame();
  62288. if (ret < highest) {
  62289. ret = highest;
  62290. }
  62291. }
  62292. }
  62293. return ret;
  62294. };
  62295. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  62296. var range = this.getAnimationRange(name);
  62297. if (!range) {
  62298. return null;
  62299. }
  62300. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  62301. };
  62302. Skeleton.prototype._markAsDirty = function () {
  62303. this._isDirty = true;
  62304. };
  62305. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  62306. this._meshesWithPoseMatrix.push(mesh);
  62307. };
  62308. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  62309. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  62310. if (index > -1) {
  62311. this._meshesWithPoseMatrix.splice(index, 1);
  62312. }
  62313. };
  62314. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  62315. this.onBeforeComputeObservable.notifyObservers(this);
  62316. for (var index = 0; index < this.bones.length; index++) {
  62317. var bone = this.bones[index];
  62318. var parentBone = bone.getParent();
  62319. if (parentBone) {
  62320. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  62321. }
  62322. else {
  62323. if (initialSkinMatrix) {
  62324. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  62325. }
  62326. else {
  62327. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  62328. }
  62329. }
  62330. if (bone._index !== -1) {
  62331. var mappedIndex = bone._index === null ? index : bone._index;
  62332. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  62333. }
  62334. }
  62335. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  62336. };
  62337. Skeleton.prototype.prepare = function () {
  62338. if (!this._isDirty) {
  62339. return;
  62340. }
  62341. if (this.needInitialSkinMatrix) {
  62342. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  62343. var mesh = this._meshesWithPoseMatrix[index];
  62344. var poseMatrix = mesh.getPoseMatrix();
  62345. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  62346. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62347. }
  62348. if (this._synchronizedWithMesh !== mesh) {
  62349. this._synchronizedWithMesh = mesh;
  62350. // Prepare bones
  62351. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  62352. var bone = this.bones[boneIndex];
  62353. if (!bone.getParent()) {
  62354. var matrix = bone.getBaseMatrix();
  62355. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  62356. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  62357. }
  62358. }
  62359. }
  62360. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  62361. }
  62362. }
  62363. else {
  62364. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  62365. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  62366. }
  62367. this._computeTransformMatrices(this._transformMatrices, null);
  62368. }
  62369. this._isDirty = false;
  62370. this._scene._activeBones.addCount(this.bones.length, false);
  62371. };
  62372. Skeleton.prototype.getAnimatables = function () {
  62373. if (!this._animatables || this._animatables.length !== this.bones.length) {
  62374. this._animatables = [];
  62375. for (var index = 0; index < this.bones.length; index++) {
  62376. this._animatables.push(this.bones[index]);
  62377. }
  62378. }
  62379. return this._animatables;
  62380. };
  62381. Skeleton.prototype.clone = function (name, id) {
  62382. var result = new Skeleton(name, id || name, this._scene);
  62383. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62384. for (var index = 0; index < this.bones.length; index++) {
  62385. var source = this.bones[index];
  62386. var parentBone = null;
  62387. var parent_1 = source.getParent();
  62388. if (parent_1) {
  62389. var parentIndex = this.bones.indexOf(parent_1);
  62390. parentBone = result.bones[parentIndex];
  62391. }
  62392. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  62393. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  62394. }
  62395. if (this._ranges) {
  62396. result._ranges = {};
  62397. for (var rangeName in this._ranges) {
  62398. var range = this._ranges[rangeName];
  62399. if (range) {
  62400. result._ranges[rangeName] = range.clone();
  62401. }
  62402. }
  62403. }
  62404. this._isDirty = true;
  62405. return result;
  62406. };
  62407. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  62408. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  62409. this.bones.forEach(function (bone) {
  62410. bone.animations.forEach(function (animation) {
  62411. animation.enableBlending = true;
  62412. animation.blendingSpeed = blendingSpeed;
  62413. });
  62414. });
  62415. };
  62416. Skeleton.prototype.dispose = function () {
  62417. this._meshesWithPoseMatrix = [];
  62418. // Animations
  62419. this.getScene().stopAnimation(this);
  62420. // Remove from scene
  62421. this.getScene().removeSkeleton(this);
  62422. };
  62423. Skeleton.prototype.serialize = function () {
  62424. var serializationObject = {};
  62425. serializationObject.name = this.name;
  62426. serializationObject.id = this.id;
  62427. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  62428. serializationObject.bones = [];
  62429. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  62430. for (var index = 0; index < this.bones.length; index++) {
  62431. var bone = this.bones[index];
  62432. var parent_2 = bone.getParent();
  62433. var serializedBone = {
  62434. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  62435. name: bone.name,
  62436. matrix: bone.getBaseMatrix().toArray(),
  62437. rest: bone.getRestPose().toArray()
  62438. };
  62439. serializationObject.bones.push(serializedBone);
  62440. if (bone.length) {
  62441. serializedBone.length = bone.length;
  62442. }
  62443. if (bone.animations && bone.animations.length > 0) {
  62444. serializedBone.animation = bone.animations[0].serialize();
  62445. }
  62446. serializationObject.ranges = [];
  62447. for (var name in this._ranges) {
  62448. var source = this._ranges[name];
  62449. if (!source) {
  62450. continue;
  62451. }
  62452. var range = {};
  62453. range.name = name;
  62454. range.from = source.from;
  62455. range.to = source.to;
  62456. serializationObject.ranges.push(range);
  62457. }
  62458. }
  62459. return serializationObject;
  62460. };
  62461. Skeleton.Parse = function (parsedSkeleton, scene) {
  62462. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  62463. if (parsedSkeleton.dimensionsAtRest) {
  62464. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  62465. }
  62466. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  62467. var index;
  62468. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  62469. var parsedBone = parsedSkeleton.bones[index];
  62470. var parentBone = null;
  62471. if (parsedBone.parentBoneIndex > -1) {
  62472. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  62473. }
  62474. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  62475. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  62476. if (parsedBone.length) {
  62477. bone.length = parsedBone.length;
  62478. }
  62479. if (parsedBone.animation) {
  62480. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  62481. }
  62482. }
  62483. // placed after bones, so createAnimationRange can cascade down
  62484. if (parsedSkeleton.ranges) {
  62485. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  62486. var data = parsedSkeleton.ranges[index];
  62487. skeleton.createAnimationRange(data.name, data.from, data.to);
  62488. }
  62489. }
  62490. return skeleton;
  62491. };
  62492. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  62493. if (forceUpdate === void 0) { forceUpdate = false; }
  62494. var renderId = this._scene.getRenderId();
  62495. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  62496. this.bones[0].computeAbsoluteTransforms();
  62497. this._lastAbsoluteTransformsUpdateId = renderId;
  62498. }
  62499. };
  62500. Skeleton.prototype.getPoseMatrix = function () {
  62501. var poseMatrix = null;
  62502. if (this._meshesWithPoseMatrix.length > 0) {
  62503. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  62504. }
  62505. return poseMatrix;
  62506. };
  62507. Skeleton.prototype.sortBones = function () {
  62508. var bones = new Array();
  62509. var visited = new Array(this.bones.length);
  62510. for (var index = 0; index < this.bones.length; index++) {
  62511. this._sortBones(index, bones, visited);
  62512. }
  62513. this.bones = bones;
  62514. };
  62515. Skeleton.prototype._sortBones = function (index, bones, visited) {
  62516. if (visited[index]) {
  62517. return;
  62518. }
  62519. visited[index] = true;
  62520. var bone = this.bones[index];
  62521. if (bone._index === undefined) {
  62522. bone._index = index;
  62523. }
  62524. var parentBone = bone.getParent();
  62525. if (parentBone) {
  62526. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  62527. }
  62528. bones.push(bone);
  62529. };
  62530. return Skeleton;
  62531. }());
  62532. BABYLON.Skeleton = Skeleton;
  62533. })(BABYLON || (BABYLON = {}));
  62534. //# sourceMappingURL=babylon.skeleton.js.map
  62535. var BABYLON;
  62536. (function (BABYLON) {
  62537. var SphericalPolynomial = /** @class */ (function () {
  62538. function SphericalPolynomial() {
  62539. this.x = BABYLON.Vector3.Zero();
  62540. this.y = BABYLON.Vector3.Zero();
  62541. this.z = BABYLON.Vector3.Zero();
  62542. this.xx = BABYLON.Vector3.Zero();
  62543. this.yy = BABYLON.Vector3.Zero();
  62544. this.zz = BABYLON.Vector3.Zero();
  62545. this.xy = BABYLON.Vector3.Zero();
  62546. this.yz = BABYLON.Vector3.Zero();
  62547. this.zx = BABYLON.Vector3.Zero();
  62548. }
  62549. SphericalPolynomial.prototype.addAmbient = function (color) {
  62550. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62551. this.xx = this.xx.add(colorVector);
  62552. this.yy = this.yy.add(colorVector);
  62553. this.zz = this.zz.add(colorVector);
  62554. };
  62555. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  62556. var result = new SphericalPolynomial();
  62557. result.x = harmonics.L11.scale(1.02333);
  62558. result.y = harmonics.L1_1.scale(1.02333);
  62559. result.z = harmonics.L10.scale(1.02333);
  62560. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  62561. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  62562. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  62563. result.yz = harmonics.L2_1.scale(0.858086);
  62564. result.zx = harmonics.L21.scale(0.858086);
  62565. result.xy = harmonics.L2_2.scale(0.858086);
  62566. result.scale(1.0 / Math.PI);
  62567. return result;
  62568. };
  62569. SphericalPolynomial.prototype.scale = function (scale) {
  62570. this.x = this.x.scale(scale);
  62571. this.y = this.y.scale(scale);
  62572. this.z = this.z.scale(scale);
  62573. this.xx = this.xx.scale(scale);
  62574. this.yy = this.yy.scale(scale);
  62575. this.zz = this.zz.scale(scale);
  62576. this.yz = this.yz.scale(scale);
  62577. this.zx = this.zx.scale(scale);
  62578. this.xy = this.xy.scale(scale);
  62579. };
  62580. return SphericalPolynomial;
  62581. }());
  62582. BABYLON.SphericalPolynomial = SphericalPolynomial;
  62583. var SphericalHarmonics = /** @class */ (function () {
  62584. function SphericalHarmonics() {
  62585. this.L00 = BABYLON.Vector3.Zero();
  62586. this.L1_1 = BABYLON.Vector3.Zero();
  62587. this.L10 = BABYLON.Vector3.Zero();
  62588. this.L11 = BABYLON.Vector3.Zero();
  62589. this.L2_2 = BABYLON.Vector3.Zero();
  62590. this.L2_1 = BABYLON.Vector3.Zero();
  62591. this.L20 = BABYLON.Vector3.Zero();
  62592. this.L21 = BABYLON.Vector3.Zero();
  62593. this.L22 = BABYLON.Vector3.Zero();
  62594. }
  62595. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  62596. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  62597. var c = colorVector.scale(deltaSolidAngle);
  62598. this.L00 = this.L00.add(c.scale(0.282095));
  62599. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  62600. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  62601. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  62602. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  62603. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  62604. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  62605. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  62606. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  62607. };
  62608. SphericalHarmonics.prototype.scale = function (scale) {
  62609. this.L00 = this.L00.scale(scale);
  62610. this.L1_1 = this.L1_1.scale(scale);
  62611. this.L10 = this.L10.scale(scale);
  62612. this.L11 = this.L11.scale(scale);
  62613. this.L2_2 = this.L2_2.scale(scale);
  62614. this.L2_1 = this.L2_1.scale(scale);
  62615. this.L20 = this.L20.scale(scale);
  62616. this.L21 = this.L21.scale(scale);
  62617. this.L22 = this.L22.scale(scale);
  62618. };
  62619. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  62620. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  62621. //
  62622. // E_lm = A_l * L_lm
  62623. //
  62624. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  62625. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  62626. // the scaling factors are given in equation 9.
  62627. // Constant (Band 0)
  62628. this.L00 = this.L00.scale(3.141593);
  62629. // Linear (Band 1)
  62630. this.L1_1 = this.L1_1.scale(2.094395);
  62631. this.L10 = this.L10.scale(2.094395);
  62632. this.L11 = this.L11.scale(2.094395);
  62633. // Quadratic (Band 2)
  62634. this.L2_2 = this.L2_2.scale(0.785398);
  62635. this.L2_1 = this.L2_1.scale(0.785398);
  62636. this.L20 = this.L20.scale(0.785398);
  62637. this.L21 = this.L21.scale(0.785398);
  62638. this.L22 = this.L22.scale(0.785398);
  62639. };
  62640. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  62641. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  62642. // L = (1/pi) * E * rho
  62643. //
  62644. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  62645. this.scale(1.0 / Math.PI);
  62646. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  62647. // (The pixel shader must apply albedo after texture fetches, etc).
  62648. };
  62649. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  62650. var result = new SphericalHarmonics();
  62651. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  62652. result.L1_1 = polynomial.y.scale(0.977204);
  62653. result.L10 = polynomial.z.scale(0.977204);
  62654. result.L11 = polynomial.x.scale(0.977204);
  62655. result.L2_2 = polynomial.xy.scale(1.16538);
  62656. result.L2_1 = polynomial.yz.scale(1.16538);
  62657. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  62658. result.L21 = polynomial.zx.scale(1.16538);
  62659. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  62660. result.scale(Math.PI);
  62661. return result;
  62662. };
  62663. return SphericalHarmonics;
  62664. }());
  62665. BABYLON.SphericalHarmonics = SphericalHarmonics;
  62666. })(BABYLON || (BABYLON = {}));
  62667. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  62668. var BABYLON;
  62669. (function (BABYLON) {
  62670. var Internals;
  62671. (function (Internals) {
  62672. var FileFaceOrientation = /** @class */ (function () {
  62673. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  62674. this.name = name;
  62675. this.worldAxisForNormal = worldAxisForNormal;
  62676. this.worldAxisForFileX = worldAxisForFileX;
  62677. this.worldAxisForFileY = worldAxisForFileY;
  62678. }
  62679. return FileFaceOrientation;
  62680. }());
  62681. ;
  62682. /**
  62683. * Helper class dealing with the extraction of spherical polynomial dataArray
  62684. * from a cube map.
  62685. */
  62686. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  62687. function CubeMapToSphericalPolynomialTools() {
  62688. }
  62689. /**
  62690. * Converts a texture to the according Spherical Polynomial data.
  62691. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62692. *
  62693. * @param texture The texture to extract the information from.
  62694. * @return The Spherical Polynomial data.
  62695. */
  62696. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  62697. if (!texture.isCube) {
  62698. // Only supports cube Textures currently.
  62699. return null;
  62700. }
  62701. var size = texture.getSize().width;
  62702. var right = texture.readPixels(0);
  62703. var left = texture.readPixels(1);
  62704. var up;
  62705. var down;
  62706. if (texture.isRenderTarget) {
  62707. up = texture.readPixels(3);
  62708. down = texture.readPixels(2);
  62709. }
  62710. else {
  62711. up = texture.readPixels(2);
  62712. down = texture.readPixels(3);
  62713. }
  62714. var front = texture.readPixels(4);
  62715. var back = texture.readPixels(5);
  62716. var gammaSpace = texture.gammaSpace;
  62717. // Always read as RGBA.
  62718. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  62719. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62720. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62721. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62722. }
  62723. var cubeInfo = {
  62724. size: size,
  62725. right: right,
  62726. left: left,
  62727. up: up,
  62728. down: down,
  62729. front: front,
  62730. back: back,
  62731. format: format,
  62732. type: type,
  62733. gammaSpace: gammaSpace,
  62734. };
  62735. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  62736. };
  62737. /**
  62738. * Converts a cubemap to the according Spherical Polynomial data.
  62739. * This extracts the first 3 orders only as they are the only one used in the lighting.
  62740. *
  62741. * @param cubeInfo The Cube map to extract the information from.
  62742. * @return The Spherical Polynomial data.
  62743. */
  62744. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  62745. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  62746. var totalSolidAngle = 0.0;
  62747. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  62748. var du = 2.0 / cubeInfo.size;
  62749. var dv = du;
  62750. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  62751. var minUV = du * 0.5 - 1.0;
  62752. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  62753. var fileFace = this.FileFaces[faceIndex];
  62754. var dataArray = cubeInfo[fileFace.name];
  62755. var v = minUV;
  62756. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  62757. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  62758. // Because SP is still linear, so summation is fine in that basis.
  62759. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  62760. for (var y = 0; y < cubeInfo.size; y++) {
  62761. var u = minUV;
  62762. for (var x = 0; x < cubeInfo.size; x++) {
  62763. // World direction (not normalised)
  62764. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  62765. worldDirection.normalize();
  62766. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  62767. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  62768. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  62769. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  62770. // Handle Integer types.
  62771. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  62772. r /= 255;
  62773. g /= 255;
  62774. b /= 255;
  62775. }
  62776. // Handle Gamma space textures.
  62777. if (cubeInfo.gammaSpace) {
  62778. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  62779. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  62780. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  62781. }
  62782. var color = new BABYLON.Color3(r, g, b);
  62783. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  62784. totalSolidAngle += deltaSolidAngle;
  62785. u += du;
  62786. }
  62787. v += dv;
  62788. }
  62789. }
  62790. // Solid angle for entire sphere is 4*pi
  62791. var sphereSolidAngle = 4.0 * Math.PI;
  62792. // Adjust the solid angle to allow for how many faces we processed.
  62793. var facesProcessed = 6.0;
  62794. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  62795. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  62796. // This is needed because the numerical integration over the cube uses a
  62797. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  62798. // and also to compensate for accumulative error due to float precision in the summation.
  62799. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  62800. sphericalHarmonics.scale(correctionFactor);
  62801. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  62802. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  62803. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  62804. };
  62805. CubeMapToSphericalPolynomialTools.FileFaces = [
  62806. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  62807. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  62808. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  62809. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  62810. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  62811. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  62812. ];
  62813. return CubeMapToSphericalPolynomialTools;
  62814. }());
  62815. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  62816. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62817. })(BABYLON || (BABYLON = {}));
  62818. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  62819. var BABYLON;
  62820. (function (BABYLON) {
  62821. var Internals;
  62822. (function (Internals) {
  62823. /**
  62824. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  62825. */
  62826. var PanoramaToCubeMapTools = /** @class */ (function () {
  62827. function PanoramaToCubeMapTools() {
  62828. }
  62829. /**
  62830. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  62831. *
  62832. * @param float32Array The source data.
  62833. * @param inputWidth The width of the input panorama.
  62834. * @param inputhHeight The height of the input panorama.
  62835. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  62836. * @return The cubemap data
  62837. */
  62838. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  62839. if (!float32Array) {
  62840. throw "ConvertPanoramaToCubemap: input cannot be null";
  62841. }
  62842. if (float32Array.length != inputWidth * inputHeight * 3) {
  62843. throw "ConvertPanoramaToCubemap: input size is wrong";
  62844. }
  62845. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  62846. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  62847. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  62848. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  62849. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  62850. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  62851. return {
  62852. front: textureFront,
  62853. back: textureBack,
  62854. left: textureLeft,
  62855. right: textureRight,
  62856. up: textureUp,
  62857. down: textureDown,
  62858. size: size,
  62859. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  62860. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  62861. gammaSpace: false,
  62862. };
  62863. };
  62864. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  62865. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  62866. var textureArray = new Float32Array(buffer);
  62867. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  62868. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  62869. var dy = 1 / texSize;
  62870. var fy = 0;
  62871. for (var y = 0; y < texSize; y++) {
  62872. var xv1 = faceData[0];
  62873. var xv2 = faceData[2];
  62874. for (var x = 0; x < texSize; x++) {
  62875. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  62876. v.normalize();
  62877. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  62878. // 3 channels per pixels
  62879. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  62880. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  62881. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  62882. xv1 = xv1.add(rotDX1);
  62883. xv2 = xv2.add(rotDX2);
  62884. }
  62885. fy += dy;
  62886. }
  62887. return textureArray;
  62888. };
  62889. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  62890. var theta = Math.atan2(vDir.z, vDir.x);
  62891. var phi = Math.acos(vDir.y);
  62892. while (theta < -Math.PI)
  62893. theta += 2 * Math.PI;
  62894. while (theta > Math.PI)
  62895. theta -= 2 * Math.PI;
  62896. var dx = theta / Math.PI;
  62897. var dy = phi / Math.PI;
  62898. // recenter.
  62899. dx = dx * 0.5 + 0.5;
  62900. var px = Math.round(dx * inputWidth);
  62901. if (px < 0)
  62902. px = 0;
  62903. else if (px >= inputWidth)
  62904. px = inputWidth - 1;
  62905. var py = Math.round(dy * inputHeight);
  62906. if (py < 0)
  62907. py = 0;
  62908. else if (py >= inputHeight)
  62909. py = inputHeight - 1;
  62910. var inputY = (inputHeight - py - 1);
  62911. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  62912. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  62913. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  62914. return {
  62915. r: r,
  62916. g: g,
  62917. b: b
  62918. };
  62919. };
  62920. PanoramaToCubeMapTools.FACE_FRONT = [
  62921. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62922. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62923. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62924. new BABYLON.Vector3(1.0, 1.0, -1.0)
  62925. ];
  62926. PanoramaToCubeMapTools.FACE_BACK = [
  62927. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62928. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62929. new BABYLON.Vector3(1.0, 1.0, 1.0),
  62930. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  62931. ];
  62932. PanoramaToCubeMapTools.FACE_RIGHT = [
  62933. new BABYLON.Vector3(1.0, -1.0, -1.0),
  62934. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62935. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62936. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62937. ];
  62938. PanoramaToCubeMapTools.FACE_LEFT = [
  62939. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62940. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62941. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62942. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  62943. ];
  62944. PanoramaToCubeMapTools.FACE_DOWN = [
  62945. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  62946. new BABYLON.Vector3(1.0, 1.0, -1.0),
  62947. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  62948. new BABYLON.Vector3(1.0, 1.0, 1.0)
  62949. ];
  62950. PanoramaToCubeMapTools.FACE_UP = [
  62951. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  62952. new BABYLON.Vector3(1.0, -1.0, 1.0),
  62953. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  62954. new BABYLON.Vector3(1.0, -1.0, -1.0)
  62955. ];
  62956. return PanoramaToCubeMapTools;
  62957. }());
  62958. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  62959. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62960. })(BABYLON || (BABYLON = {}));
  62961. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  62962. var BABYLON;
  62963. (function (BABYLON) {
  62964. var Internals;
  62965. (function (Internals) {
  62966. ;
  62967. /**
  62968. * This groups tools to convert HDR texture to native colors array.
  62969. */
  62970. var HDRTools = /** @class */ (function () {
  62971. function HDRTools() {
  62972. }
  62973. HDRTools.Ldexp = function (mantissa, exponent) {
  62974. if (exponent > 1023) {
  62975. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  62976. }
  62977. if (exponent < -1074) {
  62978. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  62979. }
  62980. return mantissa * Math.pow(2, exponent);
  62981. };
  62982. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  62983. if (exponent > 0) {
  62984. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  62985. float32array[index + 0] = red * exponent;
  62986. float32array[index + 1] = green * exponent;
  62987. float32array[index + 2] = blue * exponent;
  62988. }
  62989. else {
  62990. float32array[index + 0] = 0;
  62991. float32array[index + 1] = 0;
  62992. float32array[index + 2] = 0;
  62993. }
  62994. };
  62995. HDRTools.readStringLine = function (uint8array, startIndex) {
  62996. var line = "";
  62997. var character = "";
  62998. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  62999. character = String.fromCharCode(uint8array[i]);
  63000. if (character == "\n") {
  63001. break;
  63002. }
  63003. line += character;
  63004. }
  63005. return line;
  63006. };
  63007. /**
  63008. * Reads header information from an RGBE texture stored in a native array.
  63009. * More information on this format are available here:
  63010. * https://en.wikipedia.org/wiki/RGBE_image_format
  63011. *
  63012. * @param uint8array The binary file stored in native array.
  63013. * @return The header information.
  63014. */
  63015. HDRTools.RGBE_ReadHeader = function (uint8array) {
  63016. var height = 0;
  63017. var width = 0;
  63018. var line = this.readStringLine(uint8array, 0);
  63019. if (line[0] != '#' || line[1] != '?') {
  63020. throw "Bad HDR Format.";
  63021. }
  63022. var endOfHeader = false;
  63023. var findFormat = false;
  63024. var lineIndex = 0;
  63025. do {
  63026. lineIndex += (line.length + 1);
  63027. line = this.readStringLine(uint8array, lineIndex);
  63028. if (line == "FORMAT=32-bit_rle_rgbe") {
  63029. findFormat = true;
  63030. }
  63031. else if (line.length == 0) {
  63032. endOfHeader = true;
  63033. }
  63034. } while (!endOfHeader);
  63035. if (!findFormat) {
  63036. throw "HDR Bad header format, unsupported FORMAT";
  63037. }
  63038. lineIndex += (line.length + 1);
  63039. line = this.readStringLine(uint8array, lineIndex);
  63040. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  63041. var match = sizeRegexp.exec(line);
  63042. // TODO. Support +Y and -X if needed.
  63043. if (!match || match.length < 3) {
  63044. throw "HDR Bad header format, no size";
  63045. }
  63046. width = parseInt(match[2]);
  63047. height = parseInt(match[1]);
  63048. if (width < 8 || width > 0x7fff) {
  63049. throw "HDR Bad header format, unsupported size";
  63050. }
  63051. lineIndex += (line.length + 1);
  63052. return {
  63053. height: height,
  63054. width: width,
  63055. dataPosition: lineIndex
  63056. };
  63057. };
  63058. /**
  63059. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  63060. * This RGBE texture needs to store the information as a panorama.
  63061. *
  63062. * More information on this format are available here:
  63063. * https://en.wikipedia.org/wiki/RGBE_image_format
  63064. *
  63065. * @param buffer The binary file stored in an array buffer.
  63066. * @param size The expected size of the extracted cubemap.
  63067. * @return The Cube Map information.
  63068. */
  63069. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  63070. var uint8array = new Uint8Array(buffer);
  63071. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  63072. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63073. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  63074. return cubeMapData;
  63075. };
  63076. /**
  63077. * Returns the pixels data extracted from an RGBE texture.
  63078. * This pixels will be stored left to right up to down in the R G B order in one array.
  63079. *
  63080. * More information on this format are available here:
  63081. * https://en.wikipedia.org/wiki/RGBE_image_format
  63082. *
  63083. * @param uint8array The binary file stored in an array buffer.
  63084. * @param hdrInfo The header information of the file.
  63085. * @return The pixels data in RGB right to left up to down order.
  63086. */
  63087. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  63088. // Keep for multi format supports.
  63089. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  63090. };
  63091. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  63092. var num_scanlines = hdrInfo.height;
  63093. var scanline_width = hdrInfo.width;
  63094. var a, b, c, d, count;
  63095. var dataIndex = hdrInfo.dataPosition;
  63096. var index = 0, endIndex = 0, i = 0;
  63097. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  63098. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  63099. // 3 channels of 4 bytes per pixel in float.
  63100. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  63101. var resultArray = new Float32Array(resultBuffer);
  63102. // read in each successive scanline
  63103. while (num_scanlines > 0) {
  63104. a = uint8array[dataIndex++];
  63105. b = uint8array[dataIndex++];
  63106. c = uint8array[dataIndex++];
  63107. d = uint8array[dataIndex++];
  63108. if (a != 2 || b != 2 || (c & 0x80)) {
  63109. // this file is not run length encoded
  63110. throw "HDR Bad header format, not RLE";
  63111. }
  63112. if (((c << 8) | d) != scanline_width) {
  63113. throw "HDR Bad header format, wrong scan line width";
  63114. }
  63115. index = 0;
  63116. // read each of the four channels for the scanline into the buffer
  63117. for (i = 0; i < 4; i++) {
  63118. endIndex = (i + 1) * scanline_width;
  63119. while (index < endIndex) {
  63120. a = uint8array[dataIndex++];
  63121. b = uint8array[dataIndex++];
  63122. if (a > 128) {
  63123. // a run of the same value
  63124. count = a - 128;
  63125. if ((count == 0) || (count > endIndex - index)) {
  63126. throw "HDR Bad Format, bad scanline data (run)";
  63127. }
  63128. while (count-- > 0) {
  63129. scanLineArray[index++] = b;
  63130. }
  63131. }
  63132. else {
  63133. // a non-run
  63134. count = a;
  63135. if ((count == 0) || (count > endIndex - index)) {
  63136. throw "HDR Bad Format, bad scanline data (non-run)";
  63137. }
  63138. scanLineArray[index++] = b;
  63139. if (--count > 0) {
  63140. for (var j = 0; j < count; j++) {
  63141. scanLineArray[index++] = uint8array[dataIndex++];
  63142. }
  63143. }
  63144. }
  63145. }
  63146. }
  63147. // now convert data from buffer into floats
  63148. for (i = 0; i < scanline_width; i++) {
  63149. a = scanLineArray[i];
  63150. b = scanLineArray[i + scanline_width];
  63151. c = scanLineArray[i + 2 * scanline_width];
  63152. d = scanLineArray[i + 3 * scanline_width];
  63153. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  63154. }
  63155. num_scanlines--;
  63156. }
  63157. return resultArray;
  63158. };
  63159. return HDRTools;
  63160. }());
  63161. Internals.HDRTools = HDRTools;
  63162. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  63163. })(BABYLON || (BABYLON = {}));
  63164. //# sourceMappingURL=babylon.hdr.js.map
  63165. var BABYLON;
  63166. (function (BABYLON) {
  63167. /**
  63168. * This represents a texture coming from an HDR input.
  63169. *
  63170. * The only supported format is currently panorama picture stored in RGBE format.
  63171. * Example of such files can be found on HDRLib: http://hdrlib.com/
  63172. */
  63173. var HDRCubeTexture = /** @class */ (function (_super) {
  63174. __extends(HDRCubeTexture, _super);
  63175. /**
  63176. * Instantiates an HDRTexture from the following parameters.
  63177. *
  63178. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  63179. * @param scene The scene the texture will be used in
  63180. * @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.
  63181. * @param noMipmap Forces to not generate the mipmap if true
  63182. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  63183. * @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)
  63184. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  63185. */
  63186. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  63187. if (noMipmap === void 0) { noMipmap = false; }
  63188. if (generateHarmonics === void 0) { generateHarmonics = true; }
  63189. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  63190. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  63191. if (onLoad === void 0) { onLoad = null; }
  63192. if (onError === void 0) { onError = null; }
  63193. var _this = _super.call(this, scene) || this;
  63194. _this._useInGammaSpace = false;
  63195. _this._generateHarmonics = true;
  63196. _this._isBABYLONPreprocessed = false;
  63197. _this._onLoad = null;
  63198. _this._onError = null;
  63199. /**
  63200. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  63201. */
  63202. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63203. /**
  63204. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  63205. * This is usefull at run time to apply the good shader.
  63206. */
  63207. _this.isPMREM = false;
  63208. _this._isBlocking = true;
  63209. if (!url) {
  63210. return _this;
  63211. }
  63212. _this.name = url;
  63213. _this.url = url;
  63214. _this.hasAlpha = false;
  63215. _this.isCube = true;
  63216. _this._textureMatrix = BABYLON.Matrix.Identity();
  63217. _this._onLoad = onLoad;
  63218. _this._onError = onError;
  63219. _this.gammaSpace = false;
  63220. var caps = scene.getEngine().getCaps();
  63221. if (size) {
  63222. _this._isBABYLONPreprocessed = false;
  63223. _this._noMipmap = noMipmap;
  63224. _this._size = size;
  63225. _this._useInGammaSpace = useInGammaSpace;
  63226. _this._usePMREMGenerator = usePMREMGenerator &&
  63227. caps.textureLOD &&
  63228. caps.textureFloat &&
  63229. !_this._useInGammaSpace;
  63230. }
  63231. else {
  63232. _this._isBABYLONPreprocessed = true;
  63233. _this._noMipmap = false;
  63234. _this._useInGammaSpace = false;
  63235. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  63236. !_this._useInGammaSpace;
  63237. }
  63238. _this.isPMREM = _this._usePMREMGenerator;
  63239. _this._texture = _this._getFromCache(url, _this._noMipmap);
  63240. if (!_this._texture) {
  63241. if (!scene.useDelayedTextureLoading) {
  63242. _this.loadTexture();
  63243. }
  63244. else {
  63245. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63246. }
  63247. }
  63248. return _this;
  63249. }
  63250. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  63251. /**
  63252. * Gets wether or not the texture is blocking during loading.
  63253. */
  63254. get: function () {
  63255. return this._isBlocking;
  63256. },
  63257. /**
  63258. * Sets wether or not the texture is blocking during loading.
  63259. */
  63260. set: function (value) {
  63261. this._isBlocking = value;
  63262. },
  63263. enumerable: true,
  63264. configurable: true
  63265. });
  63266. /**
  63267. * Occurs when the file is a preprocessed .babylon.hdr file.
  63268. */
  63269. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  63270. var _this = this;
  63271. var mipLevels = 0;
  63272. var floatArrayView = null;
  63273. var scene = this.getScene();
  63274. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  63275. var mips = new Array();
  63276. if (!floatArrayView) {
  63277. return mips;
  63278. }
  63279. var startIndex = 30;
  63280. for (var level = 0; level < mipLevels; level++) {
  63281. mips.push([]);
  63282. // Fill each pixel of the mip level.
  63283. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  63284. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63285. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  63286. mips[level].push(faceData);
  63287. startIndex += faceSize;
  63288. }
  63289. }
  63290. return mips;
  63291. } : null;
  63292. var callback = function (buffer) {
  63293. var scene = _this.getScene();
  63294. if (!scene) {
  63295. return null;
  63296. }
  63297. // Create Native Array Views
  63298. var intArrayView = new Int32Array(buffer);
  63299. floatArrayView = new Float32Array(buffer);
  63300. // Fill header.
  63301. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  63302. _this._size = intArrayView[1]; // CubeMap max mip face size.
  63303. // Update Texture Information.
  63304. if (!_this._texture) {
  63305. return null;
  63306. }
  63307. _this._texture.updateSize(_this._size, _this._size);
  63308. // Fill polynomial information.
  63309. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  63310. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  63311. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  63312. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  63313. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  63314. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  63315. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  63316. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  63317. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  63318. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  63319. _this.sphericalPolynomial = sphericalPolynomial;
  63320. // Fill pixel data.
  63321. mipLevels = intArrayView[29]; // Number of mip levels.
  63322. var startIndex = 30;
  63323. var data = [];
  63324. var faceSize = Math.pow(_this._size, 2) * 3;
  63325. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  63326. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  63327. startIndex += faceSize;
  63328. }
  63329. var results = [];
  63330. var byteArray = null;
  63331. // Push each faces.
  63332. for (var k = 0; k < 6; k++) {
  63333. var dataFace = null;
  63334. // To be deprecated.
  63335. if (version === 1) {
  63336. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  63337. dataFace = data[j];
  63338. }
  63339. // If special cases.
  63340. if (!mipmapGenerator && dataFace) {
  63341. if (!scene.getEngine().getCaps().textureFloat) {
  63342. // 3 channels of 1 bytes per pixel in bytes.
  63343. var byteBuffer = new ArrayBuffer(faceSize);
  63344. byteArray = new Uint8Array(byteBuffer);
  63345. }
  63346. for (var i = 0; i < _this._size * _this._size; i++) {
  63347. // Put in gamma space if requested.
  63348. if (_this._useInGammaSpace) {
  63349. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63350. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63351. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63352. }
  63353. // Convert to int texture for fallback.
  63354. if (byteArray) {
  63355. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63356. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63357. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63358. // May use luminance instead if the result is not accurate.
  63359. var max = Math.max(Math.max(r, g), b);
  63360. if (max > 255) {
  63361. var scale = 255 / max;
  63362. r *= scale;
  63363. g *= scale;
  63364. b *= scale;
  63365. }
  63366. byteArray[(i * 3) + 0] = r;
  63367. byteArray[(i * 3) + 1] = g;
  63368. byteArray[(i * 3) + 2] = b;
  63369. }
  63370. }
  63371. }
  63372. // Fill the array accordingly.
  63373. if (byteArray) {
  63374. results.push(byteArray);
  63375. }
  63376. else {
  63377. results.push(dataFace);
  63378. }
  63379. }
  63380. return results;
  63381. };
  63382. if (scene) {
  63383. 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);
  63384. }
  63385. };
  63386. /**
  63387. * Occurs when the file is raw .hdr file.
  63388. */
  63389. HDRCubeTexture.prototype.loadHDRTexture = function () {
  63390. var _this = this;
  63391. var callback = function (buffer) {
  63392. var scene = _this.getScene();
  63393. if (!scene) {
  63394. return null;
  63395. }
  63396. // Extract the raw linear data.
  63397. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  63398. // Generate harmonics if needed.
  63399. if (_this._generateHarmonics) {
  63400. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  63401. _this.sphericalPolynomial = sphericalPolynomial;
  63402. }
  63403. var results = [];
  63404. var byteArray = null;
  63405. // Push each faces.
  63406. for (var j = 0; j < 6; j++) {
  63407. // Create uintarray fallback.
  63408. if (!scene.getEngine().getCaps().textureFloat) {
  63409. // 3 channels of 1 bytes per pixel in bytes.
  63410. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  63411. byteArray = new Uint8Array(byteBuffer);
  63412. }
  63413. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  63414. // If special cases.
  63415. if (_this._useInGammaSpace || byteArray) {
  63416. for (var i = 0; i < _this._size * _this._size; i++) {
  63417. // Put in gamma space if requested.
  63418. if (_this._useInGammaSpace) {
  63419. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  63420. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  63421. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  63422. }
  63423. // Convert to int texture for fallback.
  63424. if (byteArray) {
  63425. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  63426. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  63427. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  63428. // May use luminance instead if the result is not accurate.
  63429. var max = Math.max(Math.max(r, g), b);
  63430. if (max > 255) {
  63431. var scale = 255 / max;
  63432. r *= scale;
  63433. g *= scale;
  63434. b *= scale;
  63435. }
  63436. byteArray[(i * 3) + 0] = r;
  63437. byteArray[(i * 3) + 1] = g;
  63438. byteArray[(i * 3) + 2] = b;
  63439. }
  63440. }
  63441. }
  63442. if (byteArray) {
  63443. results.push(byteArray);
  63444. }
  63445. else {
  63446. results.push(dataFace);
  63447. }
  63448. }
  63449. return results;
  63450. };
  63451. var mipmapGenerator = null;
  63452. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  63453. // if (!this._noMipmap &&
  63454. // this._usePMREMGenerator) {
  63455. // mipmapGenerator = (data: ArrayBufferView[]) => {
  63456. // // Custom setup of the generator matching with the PBR shader values.
  63457. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  63458. // this._size,
  63459. // this._size,
  63460. // 0,
  63461. // 3,
  63462. // this.getScene().getEngine().getCaps().textureFloat,
  63463. // 2048,
  63464. // 0.25,
  63465. // false,
  63466. // true);
  63467. // return generator.filterCubeMap();
  63468. // };
  63469. // }
  63470. var scene = this.getScene();
  63471. if (scene) {
  63472. 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);
  63473. }
  63474. };
  63475. /**
  63476. * Starts the loading process of the texture.
  63477. */
  63478. HDRCubeTexture.prototype.loadTexture = function () {
  63479. if (this._isBABYLONPreprocessed) {
  63480. this.loadBabylonTexture();
  63481. }
  63482. else {
  63483. this.loadHDRTexture();
  63484. }
  63485. };
  63486. HDRCubeTexture.prototype.clone = function () {
  63487. var scene = this.getScene();
  63488. if (!scene) {
  63489. return this;
  63490. }
  63491. var size = (this._isBABYLONPreprocessed ? null : this._size);
  63492. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  63493. // Base texture
  63494. newTexture.level = this.level;
  63495. newTexture.wrapU = this.wrapU;
  63496. newTexture.wrapV = this.wrapV;
  63497. newTexture.coordinatesIndex = this.coordinatesIndex;
  63498. newTexture.coordinatesMode = this.coordinatesMode;
  63499. return newTexture;
  63500. };
  63501. // Methods
  63502. HDRCubeTexture.prototype.delayLoad = function () {
  63503. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63504. return;
  63505. }
  63506. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63507. this._texture = this._getFromCache(this.url, this._noMipmap);
  63508. if (!this._texture) {
  63509. this.loadTexture();
  63510. }
  63511. };
  63512. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  63513. return this._textureMatrix;
  63514. };
  63515. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63516. this._textureMatrix = value;
  63517. };
  63518. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63519. var texture = null;
  63520. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63521. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  63522. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  63523. texture.name = parsedTexture.name;
  63524. texture.hasAlpha = parsedTexture.hasAlpha;
  63525. texture.level = parsedTexture.level;
  63526. texture.coordinatesMode = parsedTexture.coordinatesMode;
  63527. texture.isBlocking = parsedTexture.isBlocking;
  63528. }
  63529. return texture;
  63530. };
  63531. HDRCubeTexture.prototype.serialize = function () {
  63532. if (!this.name) {
  63533. return null;
  63534. }
  63535. var serializationObject = {};
  63536. serializationObject.name = this.name;
  63537. serializationObject.hasAlpha = this.hasAlpha;
  63538. serializationObject.isCube = true;
  63539. serializationObject.level = this.level;
  63540. serializationObject.size = this._size;
  63541. serializationObject.coordinatesMode = this.coordinatesMode;
  63542. serializationObject.useInGammaSpace = this._useInGammaSpace;
  63543. serializationObject.generateHarmonics = this._generateHarmonics;
  63544. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  63545. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  63546. serializationObject.customType = "BABYLON.HDRCubeTexture";
  63547. serializationObject.noMipmap = this._noMipmap;
  63548. serializationObject.isBlocking = this._isBlocking;
  63549. return serializationObject;
  63550. };
  63551. /**
  63552. * Saves as a file the data contained in the texture in a binary format.
  63553. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63554. * as the spherical used in the lighting.
  63555. * @param url The HDR file url.
  63556. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63557. * @param onError Method called if any error happens during download.
  63558. * @return The packed binary data.
  63559. */
  63560. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  63561. if (onError === void 0) { onError = null; }
  63562. var callback = function (buffer) {
  63563. var data = new Blob([buffer], { type: 'application/octet-stream' });
  63564. // Returns a URL you can use as a href.
  63565. var objUrl = window.URL.createObjectURL(data);
  63566. // Simulates a link to it and click to dowload.
  63567. var a = document.createElement("a");
  63568. document.body.appendChild(a);
  63569. a.style.display = "none";
  63570. a.href = objUrl;
  63571. a.download = "envmap.babylon.hdr";
  63572. a.click();
  63573. };
  63574. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  63575. };
  63576. /**
  63577. * Serializes the data contained in the texture in a binary format.
  63578. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  63579. * as the spherical used in the lighting.
  63580. * @param url The HDR file url.
  63581. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  63582. * @param onError Method called if any error happens during download.
  63583. * @return The packed binary data.
  63584. */
  63585. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  63586. if (onError === void 0) { onError = null; }
  63587. // Needs the url tho create the texture.
  63588. if (!url) {
  63589. return;
  63590. }
  63591. // Check Power of two size.
  63592. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  63593. return;
  63594. }
  63595. // Coming Back in 3.x.
  63596. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  63597. };
  63598. HDRCubeTexture._facesMapping = [
  63599. "right",
  63600. "left",
  63601. "up",
  63602. "down",
  63603. "front",
  63604. "back"
  63605. ];
  63606. return HDRCubeTexture;
  63607. }(BABYLON.BaseTexture));
  63608. BABYLON.HDRCubeTexture = HDRCubeTexture;
  63609. })(BABYLON || (BABYLON = {}));
  63610. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  63611. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  63612. // Huge respect for a such great lib.
  63613. // Earcut license:
  63614. // Copyright (c) 2016, Mapbox
  63615. //
  63616. // Permission to use, copy, modify, and/or distribute this software for any purpose
  63617. // with or without fee is hereby granted, provided that the above copyright notice
  63618. // and this permission notice appear in all copies.
  63619. //
  63620. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  63621. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  63622. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  63623. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  63624. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  63625. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  63626. // THIS SOFTWARE.
  63627. var Earcut;
  63628. (function (Earcut) {
  63629. /**
  63630. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  63631. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  63632. * @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).
  63633. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  63634. */
  63635. function earcut(data, holeIndices, dim) {
  63636. dim = dim || 2;
  63637. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  63638. if (!outerNode)
  63639. return triangles;
  63640. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  63641. if (hasHoles)
  63642. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  63643. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  63644. if (data.length > 80 * dim) {
  63645. minX = maxX = data[0];
  63646. minY = maxY = data[1];
  63647. for (var i = dim; i < outerLen; i += dim) {
  63648. x = data[i];
  63649. y = data[i + 1];
  63650. if (x < minX)
  63651. minX = x;
  63652. if (y < minY)
  63653. minY = y;
  63654. if (x > maxX)
  63655. maxX = x;
  63656. if (y > maxY)
  63657. maxY = y;
  63658. }
  63659. // minX, minY and size are later used to transform coords into integers for z-order calculation
  63660. size = Math.max(maxX - minX, maxY - minY);
  63661. }
  63662. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  63663. return triangles;
  63664. }
  63665. Earcut.earcut = earcut;
  63666. var Node = /** @class */ (function () {
  63667. function Node(i, x, y) {
  63668. this.i = i;
  63669. this.x = x;
  63670. this.y = y;
  63671. this.prev = null;
  63672. this.next = null;
  63673. this.z = null;
  63674. this.prevZ = null;
  63675. this.nextZ = null;
  63676. this.steiner = false;
  63677. }
  63678. return Node;
  63679. }());
  63680. // create a circular doubly linked list from polygon points in the specified winding order
  63681. function linkedList(data, start, end, dim, clockwise) {
  63682. var i, last = null;
  63683. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  63684. for (i = start; i < end; i += dim)
  63685. last = insertNode(i, data[i], data[i + 1], last);
  63686. }
  63687. else {
  63688. for (i = end - dim; i >= start; i -= dim)
  63689. last = insertNode(i, data[i], data[i + 1], last);
  63690. }
  63691. if (last && equals(last, last.next)) {
  63692. removeNode(last);
  63693. last = last.next;
  63694. }
  63695. return last;
  63696. }
  63697. // eliminate colinear or duplicate points
  63698. function filterPoints(start, end) {
  63699. if (!start)
  63700. return start;
  63701. if (!end)
  63702. end = start;
  63703. var p = start, again;
  63704. do {
  63705. again = false;
  63706. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  63707. removeNode(p);
  63708. p = end = p.prev;
  63709. if (p === p.next)
  63710. return undefined;
  63711. again = true;
  63712. }
  63713. else {
  63714. p = p.next;
  63715. }
  63716. } while (again || p !== end);
  63717. return end;
  63718. }
  63719. // main ear slicing loop which triangulates a polygon (given as a linked list)
  63720. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  63721. if (!ear)
  63722. return;
  63723. // interlink polygon nodes in z-order
  63724. if (!pass && size)
  63725. indexCurve(ear, minX, minY, size);
  63726. var stop = ear, prev, next;
  63727. // iterate through ears, slicing them one by one
  63728. while (ear.prev !== ear.next) {
  63729. prev = ear.prev;
  63730. next = ear.next;
  63731. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  63732. // cut off the triangle
  63733. triangles.push(prev.i / dim);
  63734. triangles.push(ear.i / dim);
  63735. triangles.push(next.i / dim);
  63736. removeNode(ear);
  63737. // skipping the next vertice leads to less sliver triangles
  63738. ear = next.next;
  63739. stop = next.next;
  63740. continue;
  63741. }
  63742. ear = next;
  63743. // if we looped through the whole remaining polygon and can't find any more ears
  63744. if (ear === stop) {
  63745. // try filtering points and slicing again
  63746. if (!pass) {
  63747. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  63748. // if this didn't work, try curing all small self-intersections locally
  63749. }
  63750. else if (pass === 1) {
  63751. ear = cureLocalIntersections(ear, triangles, dim);
  63752. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  63753. // as a last resort, try splitting the remaining polygon into two
  63754. }
  63755. else if (pass === 2) {
  63756. splitEarcut(ear, triangles, dim, minX, minY, size);
  63757. }
  63758. break;
  63759. }
  63760. }
  63761. }
  63762. // check whether a polygon node forms a valid ear with adjacent nodes
  63763. function isEar(ear) {
  63764. var a = ear.prev, b = ear, c = ear.next;
  63765. if (area(a, b, c) >= 0)
  63766. return false; // reflex, can't be an ear
  63767. // now make sure we don't have other points inside the potential ear
  63768. var p = ear.next.next;
  63769. while (p !== ear.prev) {
  63770. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63771. area(p.prev, p, p.next) >= 0)
  63772. return false;
  63773. p = p.next;
  63774. }
  63775. return true;
  63776. }
  63777. function isEarHashed(ear, minX, minY, size) {
  63778. var a = ear.prev, b = ear, c = ear.next;
  63779. if (area(a, b, c) >= 0)
  63780. return false; // reflex, can't be an ear
  63781. // triangle bbox; min & max are calculated like this for speed
  63782. 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);
  63783. // z-order range for the current triangle bbox;
  63784. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  63785. // first look for points inside the triangle in increasing z-order
  63786. var p = ear.nextZ;
  63787. while (p && p.z <= maxZ) {
  63788. if (p !== ear.prev &&
  63789. p !== ear.next &&
  63790. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63791. area(p.prev, p, p.next) >= 0)
  63792. return false;
  63793. p = p.nextZ;
  63794. }
  63795. // then look for points in decreasing z-order
  63796. p = ear.prevZ;
  63797. while (p && p.z >= minZ) {
  63798. if (p !== ear.prev &&
  63799. p !== ear.next &&
  63800. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  63801. area(p.prev, p, p.next) >= 0)
  63802. return false;
  63803. p = p.prevZ;
  63804. }
  63805. return true;
  63806. }
  63807. // go through all polygon nodes and cure small local self-intersections
  63808. function cureLocalIntersections(start, triangles, dim) {
  63809. var p = start;
  63810. do {
  63811. var a = p.prev, b = p.next.next;
  63812. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  63813. triangles.push(a.i / dim);
  63814. triangles.push(p.i / dim);
  63815. triangles.push(b.i / dim);
  63816. // remove two nodes involved
  63817. removeNode(p);
  63818. removeNode(p.next);
  63819. p = start = b;
  63820. }
  63821. p = p.next;
  63822. } while (p !== start);
  63823. return p;
  63824. }
  63825. // try splitting polygon into two and triangulate them independently
  63826. function splitEarcut(start, triangles, dim, minX, minY, size) {
  63827. // look for a valid diagonal that divides the polygon into two
  63828. var a = start;
  63829. do {
  63830. var b = a.next.next;
  63831. while (b !== a.prev) {
  63832. if (a.i !== b.i && isValidDiagonal(a, b)) {
  63833. // split the polygon in two by the diagonal
  63834. var c = splitPolygon(a, b);
  63835. // filter colinear points around the cuts
  63836. a = filterPoints(a, a.next);
  63837. c = filterPoints(c, c.next);
  63838. // run earcut on each half
  63839. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  63840. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  63841. return;
  63842. }
  63843. b = b.next;
  63844. }
  63845. a = a.next;
  63846. } while (a !== start);
  63847. }
  63848. // link every hole into the outer loop, producing a single-ring polygon without holes
  63849. function eliminateHoles(data, holeIndices, outerNode, dim) {
  63850. var queue = [], i, len, start, end, list;
  63851. for (i = 0, len = holeIndices.length; i < len; i++) {
  63852. start = holeIndices[i] * dim;
  63853. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  63854. list = linkedList(data, start, end, dim, false);
  63855. if (list === list.next)
  63856. list.steiner = true;
  63857. queue.push(getLeftmost(list));
  63858. }
  63859. queue.sort(compareX);
  63860. // process holes from left to right
  63861. for (i = 0; i < queue.length; i++) {
  63862. eliminateHole(queue[i], outerNode);
  63863. outerNode = filterPoints(outerNode, outerNode.next);
  63864. }
  63865. return outerNode;
  63866. }
  63867. function compareX(a, b) {
  63868. return a.x - b.x;
  63869. }
  63870. // find a bridge between vertices that connects hole with an outer ring and and link it
  63871. function eliminateHole(hole, outerNode) {
  63872. outerNode = findHoleBridge(hole, outerNode);
  63873. if (outerNode) {
  63874. var b = splitPolygon(outerNode, hole);
  63875. filterPoints(b, b.next);
  63876. }
  63877. }
  63878. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  63879. function findHoleBridge(hole, outerNode) {
  63880. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  63881. // find a segment intersected by a ray from the hole's leftmost point to the left;
  63882. // segment's endpoint with lesser x will be potential connection point
  63883. do {
  63884. if (hy <= p.y && hy >= p.next.y) {
  63885. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  63886. if (x <= hx && x > qx) {
  63887. qx = x;
  63888. if (x === hx) {
  63889. if (hy === p.y)
  63890. return p;
  63891. if (hy === p.next.y)
  63892. return p.next;
  63893. }
  63894. m = p.x < p.next.x ? p : p.next;
  63895. }
  63896. }
  63897. p = p.next;
  63898. } while (p !== outerNode);
  63899. if (!m)
  63900. return null;
  63901. if (hx === qx)
  63902. return m.prev; // hole touches outer segment; pick lower endpoint
  63903. // look for points inside the triangle of hole point, segment intersection and endpoint;
  63904. // if there are no points found, we have a valid connection;
  63905. // otherwise choose the point of the minimum angle with the ray as connection point
  63906. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  63907. p = m.next;
  63908. while (p !== stop) {
  63909. if (hx >= p.x &&
  63910. p.x >= mx &&
  63911. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  63912. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  63913. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  63914. m = p;
  63915. tanMin = tan;
  63916. }
  63917. }
  63918. p = p.next;
  63919. }
  63920. return m;
  63921. }
  63922. // interlink polygon nodes in z-order
  63923. function indexCurve(start, minX, minY, size) {
  63924. var p = start;
  63925. do {
  63926. if (p.z === null)
  63927. p.z = zOrder(p.x, p.y, minX, minY, size);
  63928. p.prevZ = p.prev;
  63929. p.nextZ = p.next;
  63930. p = p.next;
  63931. } while (p !== start);
  63932. p.prevZ.nextZ = null;
  63933. p.prevZ = null;
  63934. sortLinked(p);
  63935. }
  63936. // Simon Tatham's linked list merge sort algorithm
  63937. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  63938. function sortLinked(list) {
  63939. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  63940. do {
  63941. p = list;
  63942. list = null;
  63943. tail = null;
  63944. numMerges = 0;
  63945. while (p) {
  63946. numMerges++;
  63947. q = p;
  63948. pSize = 0;
  63949. for (i = 0; i < inSize; i++) {
  63950. pSize++;
  63951. q = q.nextZ;
  63952. if (!q)
  63953. break;
  63954. }
  63955. qSize = inSize;
  63956. while (pSize > 0 || (qSize > 0 && q)) {
  63957. if (pSize === 0) {
  63958. e = q;
  63959. q = q.nextZ;
  63960. qSize--;
  63961. }
  63962. else if (qSize === 0 || !q) {
  63963. e = p;
  63964. p = p.nextZ;
  63965. pSize--;
  63966. }
  63967. else if (p.z <= q.z) {
  63968. e = p;
  63969. p = p.nextZ;
  63970. pSize--;
  63971. }
  63972. else {
  63973. e = q;
  63974. q = q.nextZ;
  63975. qSize--;
  63976. }
  63977. if (tail)
  63978. tail.nextZ = e;
  63979. else
  63980. list = e;
  63981. e.prevZ = tail;
  63982. tail = e;
  63983. }
  63984. p = q;
  63985. }
  63986. tail.nextZ = null;
  63987. inSize *= 2;
  63988. } while (numMerges > 1);
  63989. return list;
  63990. }
  63991. // z-order of a point given coords and size of the data bounding box
  63992. function zOrder(x, y, minX, minY, size) {
  63993. // coords are transformed into non-negative 15-bit integer range
  63994. x = 32767 * (x - minX) / size;
  63995. y = 32767 * (y - minY) / size;
  63996. x = (x | (x << 8)) & 0x00FF00FF;
  63997. x = (x | (x << 4)) & 0x0F0F0F0F;
  63998. x = (x | (x << 2)) & 0x33333333;
  63999. x = (x | (x << 1)) & 0x55555555;
  64000. y = (y | (y << 8)) & 0x00FF00FF;
  64001. y = (y | (y << 4)) & 0x0F0F0F0F;
  64002. y = (y | (y << 2)) & 0x33333333;
  64003. y = (y | (y << 1)) & 0x55555555;
  64004. return x | (y << 1);
  64005. }
  64006. // find the leftmost node of a polygon ring
  64007. function getLeftmost(start) {
  64008. var p = start, leftmost = start;
  64009. do {
  64010. if (p.x < leftmost.x)
  64011. leftmost = p;
  64012. p = p.next;
  64013. } while (p !== start);
  64014. return leftmost;
  64015. }
  64016. // check if a point lies within a convex triangle
  64017. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  64018. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  64019. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  64020. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  64021. }
  64022. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  64023. function isValidDiagonal(a, b) {
  64024. return a.next.i !== b.i &&
  64025. a.prev.i !== b.i &&
  64026. !intersectsPolygon(a, b) &&
  64027. locallyInside(a, b) &&
  64028. locallyInside(b, a) &&
  64029. middleInside(a, b);
  64030. }
  64031. // signed area of a triangle
  64032. function area(p, q, r) {
  64033. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  64034. }
  64035. // check if two points are equal
  64036. function equals(p1, p2) {
  64037. return p1.x === p2.x && p1.y === p2.y;
  64038. }
  64039. // check if two segments intersect
  64040. function intersects(p1, q1, p2, q2) {
  64041. if ((equals(p1, q1) && equals(p2, q2)) ||
  64042. (equals(p1, q2) && equals(p2, q1)))
  64043. return true;
  64044. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  64045. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  64046. }
  64047. // check if a polygon diagonal intersects any polygon segments
  64048. function intersectsPolygon(a, b) {
  64049. var p = a;
  64050. do {
  64051. if (p.i !== a.i &&
  64052. p.next.i !== a.i &&
  64053. p.i !== b.i &&
  64054. p.next.i !== b.i &&
  64055. intersects(p, p.next, a, b))
  64056. return true;
  64057. p = p.next;
  64058. } while (p !== a);
  64059. return false;
  64060. }
  64061. // check if a polygon diagonal is locally inside the polygon
  64062. function locallyInside(a, b) {
  64063. return area(a.prev, a, a.next) < 0
  64064. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  64065. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  64066. }
  64067. // check if the middle point of a polygon diagonal is inside the polygon
  64068. function middleInside(a, b) {
  64069. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  64070. do {
  64071. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  64072. inside = !inside;
  64073. p = p.next;
  64074. } while (p !== a);
  64075. return inside;
  64076. }
  64077. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  64078. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  64079. function splitPolygon(a, b) {
  64080. 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;
  64081. a.next = b;
  64082. b.prev = a;
  64083. a2.next = an;
  64084. an.prev = a2;
  64085. b2.next = a2;
  64086. a2.prev = b2;
  64087. bp.next = b2;
  64088. b2.prev = bp;
  64089. return b2;
  64090. }
  64091. // create a node and optionally link it with previous one (in a circular doubly linked list)
  64092. function insertNode(i, x, y, last) {
  64093. var p = new Node(i, x, y);
  64094. if (!last) {
  64095. p.prev = p;
  64096. p.next = p;
  64097. }
  64098. else {
  64099. p.next = last.next;
  64100. p.prev = last;
  64101. last.next.prev = p;
  64102. last.next = p;
  64103. }
  64104. return p;
  64105. }
  64106. function removeNode(p) {
  64107. p.next.prev = p.prev;
  64108. p.prev.next = p.next;
  64109. if (p.prevZ)
  64110. p.prevZ.nextZ = p.nextZ;
  64111. if (p.nextZ)
  64112. p.nextZ.prevZ = p.prevZ;
  64113. }
  64114. /**
  64115. * return a percentage difference between the polygon area and its triangulation area;
  64116. * used to verify correctness of triangulation
  64117. */
  64118. function deviation(data, holeIndices, dim, triangles) {
  64119. var hasHoles = holeIndices && holeIndices.length;
  64120. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  64121. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  64122. if (hasHoles) {
  64123. for (var i = 0, len = holeIndices.length; i < len; i++) {
  64124. var start = holeIndices[i] * dim;
  64125. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  64126. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  64127. }
  64128. }
  64129. var trianglesArea = 0;
  64130. for (i = 0; i < triangles.length; i += 3) {
  64131. var a = triangles[i] * dim;
  64132. var b = triangles[i + 1] * dim;
  64133. var c = triangles[i + 2] * dim;
  64134. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  64135. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  64136. }
  64137. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  64138. }
  64139. Earcut.deviation = deviation;
  64140. ;
  64141. function signedArea(data, start, end, dim) {
  64142. var sum = 0;
  64143. for (var i = start, j = end - dim; i < end; i += dim) {
  64144. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  64145. j = i;
  64146. }
  64147. return sum;
  64148. }
  64149. /**
  64150. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  64151. */
  64152. function flatten(data) {
  64153. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  64154. for (var i = 0; i < data.length; i++) {
  64155. for (var j = 0; j < data[i].length; j++) {
  64156. for (var d = 0; d < dim; d++)
  64157. result.vertices.push(data[i][j][d]);
  64158. }
  64159. if (i > 0) {
  64160. holeIndex += data[i - 1].length;
  64161. result.holes.push(holeIndex);
  64162. }
  64163. }
  64164. return result;
  64165. }
  64166. Earcut.flatten = flatten;
  64167. ;
  64168. })(Earcut || (Earcut = {}));
  64169. //# sourceMappingURL=babylon.earcut.js.map
  64170. var BABYLON;
  64171. (function (BABYLON) {
  64172. var IndexedVector2 = /** @class */ (function (_super) {
  64173. __extends(IndexedVector2, _super);
  64174. function IndexedVector2(original, index) {
  64175. var _this = _super.call(this, original.x, original.y) || this;
  64176. _this.index = index;
  64177. return _this;
  64178. }
  64179. return IndexedVector2;
  64180. }(BABYLON.Vector2));
  64181. var PolygonPoints = /** @class */ (function () {
  64182. function PolygonPoints() {
  64183. this.elements = new Array();
  64184. }
  64185. PolygonPoints.prototype.add = function (originalPoints) {
  64186. var _this = this;
  64187. var result = new Array();
  64188. originalPoints.forEach(function (point) {
  64189. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  64190. var newPoint = new IndexedVector2(point, _this.elements.length);
  64191. result.push(newPoint);
  64192. _this.elements.push(newPoint);
  64193. }
  64194. });
  64195. return result;
  64196. };
  64197. PolygonPoints.prototype.computeBounds = function () {
  64198. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64199. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  64200. this.elements.forEach(function (point) {
  64201. // x
  64202. if (point.x < lmin.x) {
  64203. lmin.x = point.x;
  64204. }
  64205. else if (point.x > lmax.x) {
  64206. lmax.x = point.x;
  64207. }
  64208. // y
  64209. if (point.y < lmin.y) {
  64210. lmin.y = point.y;
  64211. }
  64212. else if (point.y > lmax.y) {
  64213. lmax.y = point.y;
  64214. }
  64215. });
  64216. return {
  64217. min: lmin,
  64218. max: lmax,
  64219. width: lmax.x - lmin.x,
  64220. height: lmax.y - lmin.y
  64221. };
  64222. };
  64223. return PolygonPoints;
  64224. }());
  64225. var Polygon = /** @class */ (function () {
  64226. function Polygon() {
  64227. }
  64228. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  64229. return [
  64230. new BABYLON.Vector2(xmin, ymin),
  64231. new BABYLON.Vector2(xmax, ymin),
  64232. new BABYLON.Vector2(xmax, ymax),
  64233. new BABYLON.Vector2(xmin, ymax)
  64234. ];
  64235. };
  64236. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  64237. if (cx === void 0) { cx = 0; }
  64238. if (cy === void 0) { cy = 0; }
  64239. if (numberOfSides === void 0) { numberOfSides = 32; }
  64240. var result = new Array();
  64241. var angle = 0;
  64242. var increment = (Math.PI * 2) / numberOfSides;
  64243. for (var i = 0; i < numberOfSides; i++) {
  64244. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  64245. angle -= increment;
  64246. }
  64247. return result;
  64248. };
  64249. Polygon.Parse = function (input) {
  64250. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  64251. var i, result = [];
  64252. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  64253. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  64254. }
  64255. return result;
  64256. };
  64257. Polygon.StartingAt = function (x, y) {
  64258. return BABYLON.Path2.StartingAt(x, y);
  64259. };
  64260. return Polygon;
  64261. }());
  64262. BABYLON.Polygon = Polygon;
  64263. var PolygonMeshBuilder = /** @class */ (function () {
  64264. function PolygonMeshBuilder(name, contours, scene) {
  64265. this._points = new PolygonPoints();
  64266. this._outlinepoints = new PolygonPoints();
  64267. this._holes = new Array();
  64268. this._epoints = new Array();
  64269. this._eholes = new Array();
  64270. this._name = name;
  64271. this._scene = scene;
  64272. var points;
  64273. if (contours instanceof BABYLON.Path2) {
  64274. points = contours.getPoints();
  64275. }
  64276. else {
  64277. points = contours;
  64278. }
  64279. this._addToepoint(points);
  64280. this._points.add(points);
  64281. this._outlinepoints.add(points);
  64282. }
  64283. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  64284. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  64285. var p = points_1[_i];
  64286. this._epoints.push(p.x, p.y);
  64287. }
  64288. };
  64289. PolygonMeshBuilder.prototype.addHole = function (hole) {
  64290. this._points.add(hole);
  64291. var holepoints = new PolygonPoints();
  64292. holepoints.add(hole);
  64293. this._holes.push(holepoints);
  64294. this._eholes.push(this._epoints.length / 2);
  64295. this._addToepoint(hole);
  64296. return this;
  64297. };
  64298. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  64299. var _this = this;
  64300. if (updatable === void 0) { updatable = false; }
  64301. if (depth === void 0) { depth = 0; }
  64302. var result = new BABYLON.Mesh(this._name, this._scene);
  64303. var normals = new Array();
  64304. var positions = new Array();
  64305. var uvs = new Array();
  64306. var bounds = this._points.computeBounds();
  64307. this._points.elements.forEach(function (p) {
  64308. normals.push(0, 1.0, 0);
  64309. positions.push(p.x, 0, p.y);
  64310. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  64311. });
  64312. var indices = new Array();
  64313. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  64314. for (var i = 0; i < res.length; i++) {
  64315. indices.push(res[i]);
  64316. }
  64317. if (depth > 0) {
  64318. var positionscount = (positions.length / 3); //get the current pointcount
  64319. this._points.elements.forEach(function (p) {
  64320. normals.push(0, -1.0, 0);
  64321. positions.push(p.x, -depth, p.y);
  64322. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  64323. });
  64324. var totalCount = indices.length;
  64325. for (var i = 0; i < totalCount; i += 3) {
  64326. var i0 = indices[i + 0];
  64327. var i1 = indices[i + 1];
  64328. var i2 = indices[i + 2];
  64329. indices.push(i2 + positionscount);
  64330. indices.push(i1 + positionscount);
  64331. indices.push(i0 + positionscount);
  64332. }
  64333. //Add the sides
  64334. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  64335. this._holes.forEach(function (hole) {
  64336. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  64337. });
  64338. }
  64339. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  64340. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  64341. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  64342. result.setIndices(indices);
  64343. return result;
  64344. };
  64345. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  64346. var StartIndex = positions.length / 3;
  64347. var ulength = 0;
  64348. for (var i = 0; i < points.elements.length; i++) {
  64349. var p = points.elements[i];
  64350. var p1;
  64351. if ((i + 1) > points.elements.length - 1) {
  64352. p1 = points.elements[0];
  64353. }
  64354. else {
  64355. p1 = points.elements[i + 1];
  64356. }
  64357. positions.push(p.x, 0, p.y);
  64358. positions.push(p.x, -depth, p.y);
  64359. positions.push(p1.x, 0, p1.y);
  64360. positions.push(p1.x, -depth, p1.y);
  64361. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  64362. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  64363. var v3 = v2.subtract(v1);
  64364. var v4 = new BABYLON.Vector3(0, 1, 0);
  64365. var vn = BABYLON.Vector3.Cross(v3, v4);
  64366. vn = vn.normalize();
  64367. uvs.push(ulength / bounds.width, 0);
  64368. uvs.push(ulength / bounds.width, 1);
  64369. ulength += v3.length();
  64370. uvs.push((ulength / bounds.width), 0);
  64371. uvs.push((ulength / bounds.width), 1);
  64372. if (!flip) {
  64373. normals.push(-vn.x, -vn.y, -vn.z);
  64374. normals.push(-vn.x, -vn.y, -vn.z);
  64375. normals.push(-vn.x, -vn.y, -vn.z);
  64376. normals.push(-vn.x, -vn.y, -vn.z);
  64377. indices.push(StartIndex);
  64378. indices.push(StartIndex + 1);
  64379. indices.push(StartIndex + 2);
  64380. indices.push(StartIndex + 1);
  64381. indices.push(StartIndex + 3);
  64382. indices.push(StartIndex + 2);
  64383. }
  64384. else {
  64385. normals.push(vn.x, vn.y, vn.z);
  64386. normals.push(vn.x, vn.y, vn.z);
  64387. normals.push(vn.x, vn.y, vn.z);
  64388. normals.push(vn.x, vn.y, vn.z);
  64389. indices.push(StartIndex);
  64390. indices.push(StartIndex + 2);
  64391. indices.push(StartIndex + 1);
  64392. indices.push(StartIndex + 1);
  64393. indices.push(StartIndex + 2);
  64394. indices.push(StartIndex + 3);
  64395. }
  64396. StartIndex += 4;
  64397. }
  64398. ;
  64399. };
  64400. return PolygonMeshBuilder;
  64401. }());
  64402. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  64403. })(BABYLON || (BABYLON = {}));
  64404. //# sourceMappingURL=babylon.polygonMesh.js.map
  64405. var BABYLON;
  64406. (function (BABYLON) {
  64407. // Unique ID when we import meshes from Babylon to CSG
  64408. var currentCSGMeshId = 0;
  64409. // # class Vertex
  64410. // Represents a vertex of a polygon. Use your own vertex class instead of this
  64411. // one to provide additional features like texture coordinates and vertex
  64412. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  64413. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  64414. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  64415. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  64416. // is not used anywhere else.
  64417. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  64418. var Vertex = /** @class */ (function () {
  64419. function Vertex(pos, normal, uv) {
  64420. this.pos = pos;
  64421. this.normal = normal;
  64422. this.uv = uv;
  64423. }
  64424. Vertex.prototype.clone = function () {
  64425. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  64426. };
  64427. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  64428. // orientation of a polygon is flipped.
  64429. Vertex.prototype.flip = function () {
  64430. this.normal = this.normal.scale(-1);
  64431. };
  64432. // Create a new vertex between this vertex and `other` by linearly
  64433. // interpolating all properties using a parameter of `t`. Subclasses should
  64434. // override this to interpolate additional properties.
  64435. Vertex.prototype.interpolate = function (other, t) {
  64436. 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));
  64437. };
  64438. return Vertex;
  64439. }());
  64440. // # class Plane
  64441. // Represents a plane in 3D space.
  64442. var Plane = /** @class */ (function () {
  64443. function Plane(normal, w) {
  64444. this.normal = normal;
  64445. this.w = w;
  64446. }
  64447. Plane.FromPoints = function (a, b, c) {
  64448. var v0 = c.subtract(a);
  64449. var v1 = b.subtract(a);
  64450. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  64451. return null;
  64452. }
  64453. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  64454. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  64455. };
  64456. Plane.prototype.clone = function () {
  64457. return new Plane(this.normal.clone(), this.w);
  64458. };
  64459. Plane.prototype.flip = function () {
  64460. this.normal.scaleInPlace(-1);
  64461. this.w = -this.w;
  64462. };
  64463. // Split `polygon` by this plane if needed, then put the polygon or polygon
  64464. // fragments in the appropriate lists. Coplanar polygons go into either
  64465. // `coplanarFront` or `coplanarBack` depending on their orientation with
  64466. // respect to this plane. Polygons in front or in back of this plane go into
  64467. // either `front` or `back`.
  64468. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  64469. var COPLANAR = 0;
  64470. var FRONT = 1;
  64471. var BACK = 2;
  64472. var SPANNING = 3;
  64473. // Classify each point as well as the entire polygon into one of the above
  64474. // four classes.
  64475. var polygonType = 0;
  64476. var types = [];
  64477. var i;
  64478. var t;
  64479. for (i = 0; i < polygon.vertices.length; i++) {
  64480. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  64481. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  64482. polygonType |= type;
  64483. types.push(type);
  64484. }
  64485. // Put the polygon in the correct list, splitting it when necessary.
  64486. switch (polygonType) {
  64487. case COPLANAR:
  64488. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  64489. break;
  64490. case FRONT:
  64491. front.push(polygon);
  64492. break;
  64493. case BACK:
  64494. back.push(polygon);
  64495. break;
  64496. case SPANNING:
  64497. var f = [], b = [];
  64498. for (i = 0; i < polygon.vertices.length; i++) {
  64499. var j = (i + 1) % polygon.vertices.length;
  64500. var ti = types[i], tj = types[j];
  64501. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  64502. if (ti !== BACK)
  64503. f.push(vi);
  64504. if (ti !== FRONT)
  64505. b.push(ti !== BACK ? vi.clone() : vi);
  64506. if ((ti | tj) === SPANNING) {
  64507. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  64508. var v = vi.interpolate(vj, t);
  64509. f.push(v);
  64510. b.push(v.clone());
  64511. }
  64512. }
  64513. var poly;
  64514. if (f.length >= 3) {
  64515. poly = new Polygon(f, polygon.shared);
  64516. if (poly.plane)
  64517. front.push(poly);
  64518. }
  64519. if (b.length >= 3) {
  64520. poly = new Polygon(b, polygon.shared);
  64521. if (poly.plane)
  64522. back.push(poly);
  64523. }
  64524. break;
  64525. }
  64526. };
  64527. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  64528. // point is on the plane.
  64529. Plane.EPSILON = 1e-5;
  64530. return Plane;
  64531. }());
  64532. // # class Polygon
  64533. // Represents a convex polygon. The vertices used to initialize a polygon must
  64534. // be coplanar and form a convex loop.
  64535. //
  64536. // Each convex polygon has a `shared` property, which is shared between all
  64537. // polygons that are clones of each other or were split from the same polygon.
  64538. // This can be used to define per-polygon properties (such as surface color).
  64539. var Polygon = /** @class */ (function () {
  64540. function Polygon(vertices, shared) {
  64541. this.vertices = vertices;
  64542. this.shared = shared;
  64543. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  64544. }
  64545. Polygon.prototype.clone = function () {
  64546. var vertices = this.vertices.map(function (v) { return v.clone(); });
  64547. return new Polygon(vertices, this.shared);
  64548. };
  64549. Polygon.prototype.flip = function () {
  64550. this.vertices.reverse().map(function (v) { v.flip(); });
  64551. this.plane.flip();
  64552. };
  64553. return Polygon;
  64554. }());
  64555. // # class Node
  64556. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  64557. // by picking a polygon to split along. That polygon (and all other coplanar
  64558. // polygons) are added directly to that node and the other polygons are added to
  64559. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  64560. // no distinction between internal and leaf nodes.
  64561. var Node = /** @class */ (function () {
  64562. function Node(polygons) {
  64563. this.plane = null;
  64564. this.front = null;
  64565. this.back = null;
  64566. this.polygons = new Array();
  64567. if (polygons) {
  64568. this.build(polygons);
  64569. }
  64570. }
  64571. Node.prototype.clone = function () {
  64572. var node = new Node();
  64573. node.plane = this.plane && this.plane.clone();
  64574. node.front = this.front && this.front.clone();
  64575. node.back = this.back && this.back.clone();
  64576. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  64577. return node;
  64578. };
  64579. // Convert solid space to empty space and empty space to solid space.
  64580. Node.prototype.invert = function () {
  64581. for (var i = 0; i < this.polygons.length; i++) {
  64582. this.polygons[i].flip();
  64583. }
  64584. if (this.plane) {
  64585. this.plane.flip();
  64586. }
  64587. if (this.front) {
  64588. this.front.invert();
  64589. }
  64590. if (this.back) {
  64591. this.back.invert();
  64592. }
  64593. var temp = this.front;
  64594. this.front = this.back;
  64595. this.back = temp;
  64596. };
  64597. // Recursively remove all polygons in `polygons` that are inside this BSP
  64598. // tree.
  64599. Node.prototype.clipPolygons = function (polygons) {
  64600. if (!this.plane)
  64601. return polygons.slice();
  64602. var front = new Array(), back = new Array();
  64603. for (var i = 0; i < polygons.length; i++) {
  64604. this.plane.splitPolygon(polygons[i], front, back, front, back);
  64605. }
  64606. if (this.front) {
  64607. front = this.front.clipPolygons(front);
  64608. }
  64609. if (this.back) {
  64610. back = this.back.clipPolygons(back);
  64611. }
  64612. else {
  64613. back = [];
  64614. }
  64615. return front.concat(back);
  64616. };
  64617. // Remove all polygons in this BSP tree that are inside the other BSP tree
  64618. // `bsp`.
  64619. Node.prototype.clipTo = function (bsp) {
  64620. this.polygons = bsp.clipPolygons(this.polygons);
  64621. if (this.front)
  64622. this.front.clipTo(bsp);
  64623. if (this.back)
  64624. this.back.clipTo(bsp);
  64625. };
  64626. // Return a list of all polygons in this BSP tree.
  64627. Node.prototype.allPolygons = function () {
  64628. var polygons = this.polygons.slice();
  64629. if (this.front)
  64630. polygons = polygons.concat(this.front.allPolygons());
  64631. if (this.back)
  64632. polygons = polygons.concat(this.back.allPolygons());
  64633. return polygons;
  64634. };
  64635. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  64636. // new polygons are filtered down to the bottom of the tree and become new
  64637. // nodes there. Each set of polygons is partitioned using the first polygon
  64638. // (no heuristic is used to pick a good split).
  64639. Node.prototype.build = function (polygons) {
  64640. if (!polygons.length)
  64641. return;
  64642. if (!this.plane)
  64643. this.plane = polygons[0].plane.clone();
  64644. var front = new Array(), back = new Array();
  64645. for (var i = 0; i < polygons.length; i++) {
  64646. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  64647. }
  64648. if (front.length) {
  64649. if (!this.front)
  64650. this.front = new Node();
  64651. this.front.build(front);
  64652. }
  64653. if (back.length) {
  64654. if (!this.back)
  64655. this.back = new Node();
  64656. this.back.build(back);
  64657. }
  64658. };
  64659. return Node;
  64660. }());
  64661. var CSG = /** @class */ (function () {
  64662. function CSG() {
  64663. this.polygons = new Array();
  64664. }
  64665. // Convert BABYLON.Mesh to BABYLON.CSG
  64666. CSG.FromMesh = function (mesh) {
  64667. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  64668. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  64669. if (mesh instanceof BABYLON.Mesh) {
  64670. mesh.computeWorldMatrix(true);
  64671. matrix = mesh.getWorldMatrix();
  64672. meshPosition = mesh.position.clone();
  64673. meshRotation = mesh.rotation.clone();
  64674. if (mesh.rotationQuaternion) {
  64675. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  64676. }
  64677. meshScaling = mesh.scaling.clone();
  64678. }
  64679. else {
  64680. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  64681. }
  64682. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  64683. var subMeshes = mesh.subMeshes;
  64684. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  64685. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  64686. vertices = [];
  64687. for (var j = 0; j < 3; j++) {
  64688. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  64689. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  64690. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  64691. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  64692. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  64693. vertex = new Vertex(position, normal, uv);
  64694. vertices.push(vertex);
  64695. }
  64696. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  64697. // To handle the case of degenerated triangle
  64698. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  64699. if (polygon.plane)
  64700. polygons.push(polygon);
  64701. }
  64702. }
  64703. var csg = CSG.FromPolygons(polygons);
  64704. csg.matrix = matrix;
  64705. csg.position = meshPosition;
  64706. csg.rotation = meshRotation;
  64707. csg.scaling = meshScaling;
  64708. csg.rotationQuaternion = meshRotationQuaternion;
  64709. currentCSGMeshId++;
  64710. return csg;
  64711. };
  64712. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  64713. CSG.FromPolygons = function (polygons) {
  64714. var csg = new CSG();
  64715. csg.polygons = polygons;
  64716. return csg;
  64717. };
  64718. CSG.prototype.clone = function () {
  64719. var csg = new CSG();
  64720. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  64721. csg.copyTransformAttributes(this);
  64722. return csg;
  64723. };
  64724. CSG.prototype.union = function (csg) {
  64725. var a = new Node(this.clone().polygons);
  64726. var b = new Node(csg.clone().polygons);
  64727. a.clipTo(b);
  64728. b.clipTo(a);
  64729. b.invert();
  64730. b.clipTo(a);
  64731. b.invert();
  64732. a.build(b.allPolygons());
  64733. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64734. };
  64735. CSG.prototype.unionInPlace = function (csg) {
  64736. var a = new Node(this.polygons);
  64737. var b = new Node(csg.polygons);
  64738. a.clipTo(b);
  64739. b.clipTo(a);
  64740. b.invert();
  64741. b.clipTo(a);
  64742. b.invert();
  64743. a.build(b.allPolygons());
  64744. this.polygons = a.allPolygons();
  64745. };
  64746. CSG.prototype.subtract = function (csg) {
  64747. var a = new Node(this.clone().polygons);
  64748. var b = new Node(csg.clone().polygons);
  64749. a.invert();
  64750. a.clipTo(b);
  64751. b.clipTo(a);
  64752. b.invert();
  64753. b.clipTo(a);
  64754. b.invert();
  64755. a.build(b.allPolygons());
  64756. a.invert();
  64757. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64758. };
  64759. CSG.prototype.subtractInPlace = function (csg) {
  64760. var a = new Node(this.polygons);
  64761. var b = new Node(csg.polygons);
  64762. a.invert();
  64763. a.clipTo(b);
  64764. b.clipTo(a);
  64765. b.invert();
  64766. b.clipTo(a);
  64767. b.invert();
  64768. a.build(b.allPolygons());
  64769. a.invert();
  64770. this.polygons = a.allPolygons();
  64771. };
  64772. CSG.prototype.intersect = function (csg) {
  64773. var a = new Node(this.clone().polygons);
  64774. var b = new Node(csg.clone().polygons);
  64775. a.invert();
  64776. b.clipTo(a);
  64777. b.invert();
  64778. a.clipTo(b);
  64779. b.clipTo(a);
  64780. a.build(b.allPolygons());
  64781. a.invert();
  64782. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  64783. };
  64784. CSG.prototype.intersectInPlace = function (csg) {
  64785. var a = new Node(this.polygons);
  64786. var b = new Node(csg.polygons);
  64787. a.invert();
  64788. b.clipTo(a);
  64789. b.invert();
  64790. a.clipTo(b);
  64791. b.clipTo(a);
  64792. a.build(b.allPolygons());
  64793. a.invert();
  64794. this.polygons = a.allPolygons();
  64795. };
  64796. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  64797. // not modified.
  64798. CSG.prototype.inverse = function () {
  64799. var csg = this.clone();
  64800. csg.inverseInPlace();
  64801. return csg;
  64802. };
  64803. CSG.prototype.inverseInPlace = function () {
  64804. this.polygons.map(function (p) { p.flip(); });
  64805. };
  64806. // This is used to keep meshes transformations so they can be restored
  64807. // when we build back a Babylon Mesh
  64808. // NB : All CSG operations are performed in world coordinates
  64809. CSG.prototype.copyTransformAttributes = function (csg) {
  64810. this.matrix = csg.matrix;
  64811. this.position = csg.position;
  64812. this.rotation = csg.rotation;
  64813. this.scaling = csg.scaling;
  64814. this.rotationQuaternion = csg.rotationQuaternion;
  64815. return this;
  64816. };
  64817. // Build Raw mesh from CSG
  64818. // Coordinates here are in world space
  64819. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  64820. var matrix = this.matrix.clone();
  64821. matrix.invert();
  64822. 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;
  64823. if (keepSubMeshes) {
  64824. // Sort Polygons, since subMeshes are indices range
  64825. polygons.sort(function (a, b) {
  64826. if (a.shared.meshId === b.shared.meshId) {
  64827. return a.shared.subMeshId - b.shared.subMeshId;
  64828. }
  64829. else {
  64830. return a.shared.meshId - b.shared.meshId;
  64831. }
  64832. });
  64833. }
  64834. for (var i = 0, il = polygons.length; i < il; i++) {
  64835. polygon = polygons[i];
  64836. // Building SubMeshes
  64837. if (!subMesh_dict[polygon.shared.meshId]) {
  64838. subMesh_dict[polygon.shared.meshId] = {};
  64839. }
  64840. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  64841. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  64842. indexStart: +Infinity,
  64843. indexEnd: -Infinity,
  64844. materialIndex: polygon.shared.materialIndex
  64845. };
  64846. }
  64847. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  64848. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  64849. polygonIndices[0] = 0;
  64850. polygonIndices[1] = j - 1;
  64851. polygonIndices[2] = j;
  64852. for (var k = 0; k < 3; k++) {
  64853. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  64854. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  64855. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  64856. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  64857. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  64858. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  64859. // Check if 2 points can be merged
  64860. if (!(typeof vertex_idx !== 'undefined' &&
  64861. normals[vertex_idx * 3] === localNormal.x &&
  64862. normals[vertex_idx * 3 + 1] === localNormal.y &&
  64863. normals[vertex_idx * 3 + 2] === localNormal.z &&
  64864. uvs[vertex_idx * 2] === uv.x &&
  64865. uvs[vertex_idx * 2 + 1] === uv.y)) {
  64866. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  64867. uvs.push(uv.x, uv.y);
  64868. normals.push(normal.x, normal.y, normal.z);
  64869. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  64870. }
  64871. indices.push(vertex_idx);
  64872. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  64873. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  64874. currentIndex++;
  64875. }
  64876. }
  64877. }
  64878. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  64879. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  64880. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  64881. mesh.setIndices(indices, null);
  64882. if (keepSubMeshes) {
  64883. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  64884. var materialIndexOffset = 0, materialMaxIndex;
  64885. mesh.subMeshes = new Array();
  64886. for (var m in subMesh_dict) {
  64887. materialMaxIndex = -1;
  64888. for (var sm in subMesh_dict[m]) {
  64889. subMesh_obj = subMesh_dict[m][sm];
  64890. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  64891. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  64892. }
  64893. materialIndexOffset += ++materialMaxIndex;
  64894. }
  64895. }
  64896. return mesh;
  64897. };
  64898. // Build Mesh from CSG taking material and transforms into account
  64899. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  64900. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  64901. mesh.material = material;
  64902. mesh.position.copyFrom(this.position);
  64903. mesh.rotation.copyFrom(this.rotation);
  64904. if (this.rotationQuaternion) {
  64905. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  64906. }
  64907. mesh.scaling.copyFrom(this.scaling);
  64908. mesh.computeWorldMatrix(true);
  64909. return mesh;
  64910. };
  64911. return CSG;
  64912. }());
  64913. BABYLON.CSG = CSG;
  64914. })(BABYLON || (BABYLON = {}));
  64915. //# sourceMappingURL=babylon.csg.js.map
  64916. var BABYLON;
  64917. (function (BABYLON) {
  64918. var LensFlare = /** @class */ (function () {
  64919. function LensFlare(size, position, color, imgUrl, system) {
  64920. this.size = size;
  64921. this.position = position;
  64922. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  64923. this.color = color || new BABYLON.Color3(1, 1, 1);
  64924. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  64925. this._system = system;
  64926. system.lensFlares.push(this);
  64927. }
  64928. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  64929. return new LensFlare(size, position, color, imgUrl, system);
  64930. };
  64931. LensFlare.prototype.dispose = function () {
  64932. if (this.texture) {
  64933. this.texture.dispose();
  64934. }
  64935. // Remove from scene
  64936. var index = this._system.lensFlares.indexOf(this);
  64937. this._system.lensFlares.splice(index, 1);
  64938. };
  64939. ;
  64940. return LensFlare;
  64941. }());
  64942. BABYLON.LensFlare = LensFlare;
  64943. })(BABYLON || (BABYLON = {}));
  64944. //# sourceMappingURL=babylon.lensFlare.js.map
  64945. var BABYLON;
  64946. (function (BABYLON) {
  64947. var LensFlareSystem = /** @class */ (function () {
  64948. function LensFlareSystem(name, emitter, scene) {
  64949. this.name = name;
  64950. this.lensFlares = new Array();
  64951. this.borderLimit = 300;
  64952. this.viewportBorder = 0;
  64953. this.layerMask = 0x0FFFFFFF;
  64954. this._vertexBuffers = {};
  64955. this._isEnabled = true;
  64956. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64957. this._emitter = emitter;
  64958. this.id = name;
  64959. scene.lensFlareSystems.push(this);
  64960. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  64961. var engine = scene.getEngine();
  64962. // VBO
  64963. var vertices = [];
  64964. vertices.push(1, 1);
  64965. vertices.push(-1, 1);
  64966. vertices.push(-1, -1);
  64967. vertices.push(1, -1);
  64968. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64969. // Indices
  64970. var indices = [];
  64971. indices.push(0);
  64972. indices.push(1);
  64973. indices.push(2);
  64974. indices.push(0);
  64975. indices.push(2);
  64976. indices.push(3);
  64977. this._indexBuffer = engine.createIndexBuffer(indices);
  64978. // Effects
  64979. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  64980. }
  64981. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  64982. get: function () {
  64983. return this._isEnabled;
  64984. },
  64985. set: function (value) {
  64986. this._isEnabled = value;
  64987. },
  64988. enumerable: true,
  64989. configurable: true
  64990. });
  64991. LensFlareSystem.prototype.getScene = function () {
  64992. return this._scene;
  64993. };
  64994. LensFlareSystem.prototype.getEmitter = function () {
  64995. return this._emitter;
  64996. };
  64997. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  64998. this._emitter = newEmitter;
  64999. };
  65000. LensFlareSystem.prototype.getEmitterPosition = function () {
  65001. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  65002. };
  65003. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  65004. var position = this.getEmitterPosition();
  65005. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  65006. this._positionX = position.x;
  65007. this._positionY = position.y;
  65008. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  65009. if (this.viewportBorder > 0) {
  65010. globalViewport.x -= this.viewportBorder;
  65011. globalViewport.y -= this.viewportBorder;
  65012. globalViewport.width += this.viewportBorder * 2;
  65013. globalViewport.height += this.viewportBorder * 2;
  65014. position.x += this.viewportBorder;
  65015. position.y += this.viewportBorder;
  65016. this._positionX += this.viewportBorder;
  65017. this._positionY += this.viewportBorder;
  65018. }
  65019. if (position.z > 0) {
  65020. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  65021. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  65022. return true;
  65023. }
  65024. return true;
  65025. }
  65026. return false;
  65027. };
  65028. LensFlareSystem.prototype._isVisible = function () {
  65029. if (!this._isEnabled || !this._scene.activeCamera) {
  65030. return false;
  65031. }
  65032. var emitterPosition = this.getEmitterPosition();
  65033. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  65034. var distance = direction.length();
  65035. direction.normalize();
  65036. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  65037. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  65038. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  65039. };
  65040. LensFlareSystem.prototype.render = function () {
  65041. if (!this._effect.isReady() || !this._scene.activeCamera)
  65042. return false;
  65043. var engine = this._scene.getEngine();
  65044. var viewport = this._scene.activeCamera.viewport;
  65045. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  65046. // Position
  65047. if (!this.computeEffectivePosition(globalViewport)) {
  65048. return false;
  65049. }
  65050. // Visibility
  65051. if (!this._isVisible()) {
  65052. return false;
  65053. }
  65054. // Intensity
  65055. var awayX;
  65056. var awayY;
  65057. if (this._positionX < this.borderLimit + globalViewport.x) {
  65058. awayX = this.borderLimit + globalViewport.x - this._positionX;
  65059. }
  65060. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  65061. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  65062. }
  65063. else {
  65064. awayX = 0;
  65065. }
  65066. if (this._positionY < this.borderLimit + globalViewport.y) {
  65067. awayY = this.borderLimit + globalViewport.y - this._positionY;
  65068. }
  65069. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  65070. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  65071. }
  65072. else {
  65073. awayY = 0;
  65074. }
  65075. var away = (awayX > awayY) ? awayX : awayY;
  65076. away -= this.viewportBorder;
  65077. if (away > this.borderLimit) {
  65078. away = this.borderLimit;
  65079. }
  65080. var intensity = 1.0 - (away / this.borderLimit);
  65081. if (intensity < 0) {
  65082. return false;
  65083. }
  65084. if (intensity > 1.0) {
  65085. intensity = 1.0;
  65086. }
  65087. if (this.viewportBorder > 0) {
  65088. globalViewport.x += this.viewportBorder;
  65089. globalViewport.y += this.viewportBorder;
  65090. globalViewport.width -= this.viewportBorder * 2;
  65091. globalViewport.height -= this.viewportBorder * 2;
  65092. this._positionX -= this.viewportBorder;
  65093. this._positionY -= this.viewportBorder;
  65094. }
  65095. // Position
  65096. var centerX = globalViewport.x + globalViewport.width / 2;
  65097. var centerY = globalViewport.y + globalViewport.height / 2;
  65098. var distX = centerX - this._positionX;
  65099. var distY = centerY - this._positionY;
  65100. // Effects
  65101. engine.enableEffect(this._effect);
  65102. engine.setState(false);
  65103. engine.setDepthBuffer(false);
  65104. // VBOs
  65105. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65106. // Flares
  65107. for (var index = 0; index < this.lensFlares.length; index++) {
  65108. var flare = this.lensFlares[index];
  65109. engine.setAlphaMode(flare.alphaMode);
  65110. var x = centerX - (distX * flare.position);
  65111. var y = centerY - (distY * flare.position);
  65112. var cw = flare.size;
  65113. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  65114. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  65115. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  65116. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  65117. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  65118. // Texture
  65119. this._effect.setTexture("textureSampler", flare.texture);
  65120. // Color
  65121. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  65122. // Draw order
  65123. engine.draw(true, 0, 6);
  65124. }
  65125. engine.setDepthBuffer(true);
  65126. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65127. return true;
  65128. };
  65129. LensFlareSystem.prototype.dispose = function () {
  65130. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65131. if (vertexBuffer) {
  65132. vertexBuffer.dispose();
  65133. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65134. }
  65135. if (this._indexBuffer) {
  65136. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65137. this._indexBuffer = null;
  65138. }
  65139. while (this.lensFlares.length) {
  65140. this.lensFlares[0].dispose();
  65141. }
  65142. // Remove from scene
  65143. var index = this._scene.lensFlareSystems.indexOf(this);
  65144. this._scene.lensFlareSystems.splice(index, 1);
  65145. };
  65146. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  65147. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  65148. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  65149. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  65150. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  65151. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  65152. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  65153. var parsedFlare = parsedLensFlareSystem.flares[index];
  65154. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  65155. }
  65156. return lensFlareSystem;
  65157. };
  65158. LensFlareSystem.prototype.serialize = function () {
  65159. var serializationObject = {};
  65160. serializationObject.id = this.id;
  65161. serializationObject.name = this.name;
  65162. serializationObject.emitterId = this.getEmitter().id;
  65163. serializationObject.borderLimit = this.borderLimit;
  65164. serializationObject.flares = [];
  65165. for (var index = 0; index < this.lensFlares.length; index++) {
  65166. var flare = this.lensFlares[index];
  65167. serializationObject.flares.push({
  65168. size: flare.size,
  65169. position: flare.position,
  65170. color: flare.color.asArray(),
  65171. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  65172. });
  65173. }
  65174. return serializationObject;
  65175. };
  65176. return LensFlareSystem;
  65177. }());
  65178. BABYLON.LensFlareSystem = LensFlareSystem;
  65179. })(BABYLON || (BABYLON = {}));
  65180. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  65181. var BABYLON;
  65182. (function (BABYLON) {
  65183. /**
  65184. * This is a holder class for the physics joint created by the physics plugin.
  65185. * It holds a set of functions to control the underlying joint.
  65186. */
  65187. var PhysicsJoint = /** @class */ (function () {
  65188. function PhysicsJoint(type, jointData) {
  65189. this.type = type;
  65190. this.jointData = jointData;
  65191. jointData.nativeParams = jointData.nativeParams || {};
  65192. }
  65193. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  65194. get: function () {
  65195. return this._physicsJoint;
  65196. },
  65197. set: function (newJoint) {
  65198. if (this._physicsJoint) {
  65199. //remove from the wolrd
  65200. }
  65201. this._physicsJoint = newJoint;
  65202. },
  65203. enumerable: true,
  65204. configurable: true
  65205. });
  65206. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  65207. set: function (physicsPlugin) {
  65208. this._physicsPlugin = physicsPlugin;
  65209. },
  65210. enumerable: true,
  65211. configurable: true
  65212. });
  65213. /**
  65214. * Execute a function that is physics-plugin specific.
  65215. * @param {Function} func the function that will be executed.
  65216. * It accepts two parameters: the physics world and the physics joint.
  65217. */
  65218. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  65219. func(this._physicsPlugin.world, this._physicsJoint);
  65220. };
  65221. //TODO check if the native joints are the same
  65222. //Joint Types
  65223. PhysicsJoint.DistanceJoint = 0;
  65224. PhysicsJoint.HingeJoint = 1;
  65225. PhysicsJoint.BallAndSocketJoint = 2;
  65226. PhysicsJoint.WheelJoint = 3;
  65227. PhysicsJoint.SliderJoint = 4;
  65228. //OIMO
  65229. PhysicsJoint.PrismaticJoint = 5;
  65230. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  65231. PhysicsJoint.UniversalJoint = 6;
  65232. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  65233. //Cannon
  65234. //Similar to a Ball-Joint. Different in params
  65235. PhysicsJoint.PointToPointJoint = 8;
  65236. //Cannon only at the moment
  65237. PhysicsJoint.SpringJoint = 9;
  65238. PhysicsJoint.LockJoint = 10;
  65239. return PhysicsJoint;
  65240. }());
  65241. BABYLON.PhysicsJoint = PhysicsJoint;
  65242. /**
  65243. * A class representing a physics distance joint.
  65244. */
  65245. var DistanceJoint = /** @class */ (function (_super) {
  65246. __extends(DistanceJoint, _super);
  65247. function DistanceJoint(jointData) {
  65248. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  65249. }
  65250. /**
  65251. * Update the predefined distance.
  65252. */
  65253. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  65254. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  65255. };
  65256. return DistanceJoint;
  65257. }(PhysicsJoint));
  65258. BABYLON.DistanceJoint = DistanceJoint;
  65259. var MotorEnabledJoint = /** @class */ (function (_super) {
  65260. __extends(MotorEnabledJoint, _super);
  65261. function MotorEnabledJoint(type, jointData) {
  65262. return _super.call(this, type, jointData) || this;
  65263. }
  65264. /**
  65265. * Set the motor values.
  65266. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65267. * @param {number} force the force to apply
  65268. * @param {number} maxForce max force for this motor.
  65269. */
  65270. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  65271. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65272. };
  65273. /**
  65274. * Set the motor's limits.
  65275. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65276. */
  65277. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65278. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65279. };
  65280. return MotorEnabledJoint;
  65281. }(PhysicsJoint));
  65282. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  65283. /**
  65284. * This class represents a single hinge physics joint
  65285. */
  65286. var HingeJoint = /** @class */ (function (_super) {
  65287. __extends(HingeJoint, _super);
  65288. function HingeJoint(jointData) {
  65289. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  65290. }
  65291. /**
  65292. * Set the motor values.
  65293. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65294. * @param {number} force the force to apply
  65295. * @param {number} maxForce max force for this motor.
  65296. */
  65297. HingeJoint.prototype.setMotor = function (force, maxForce) {
  65298. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  65299. };
  65300. /**
  65301. * Set the motor's limits.
  65302. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65303. */
  65304. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  65305. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  65306. };
  65307. return HingeJoint;
  65308. }(MotorEnabledJoint));
  65309. BABYLON.HingeJoint = HingeJoint;
  65310. /**
  65311. * This class represents a dual hinge physics joint (same as wheel joint)
  65312. */
  65313. var Hinge2Joint = /** @class */ (function (_super) {
  65314. __extends(Hinge2Joint, _super);
  65315. function Hinge2Joint(jointData) {
  65316. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  65317. }
  65318. /**
  65319. * Set the motor values.
  65320. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65321. * @param {number} force the force to apply
  65322. * @param {number} maxForce max force for this motor.
  65323. * @param {motorIndex} the motor's index, 0 or 1.
  65324. */
  65325. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  65326. if (motorIndex === void 0) { motorIndex = 0; }
  65327. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  65328. };
  65329. /**
  65330. * Set the motor limits.
  65331. * Attention, this function is plugin specific. Engines won't react 100% the same.
  65332. * @param {number} upperLimit the upper limit
  65333. * @param {number} lowerLimit lower limit
  65334. * @param {motorIndex} the motor's index, 0 or 1.
  65335. */
  65336. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  65337. if (motorIndex === void 0) { motorIndex = 0; }
  65338. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  65339. };
  65340. return Hinge2Joint;
  65341. }(MotorEnabledJoint));
  65342. BABYLON.Hinge2Joint = Hinge2Joint;
  65343. })(BABYLON || (BABYLON = {}));
  65344. //# sourceMappingURL=babylon.physicsJoint.js.map
  65345. var BABYLON;
  65346. (function (BABYLON) {
  65347. var PhysicsImpostor = /** @class */ (function () {
  65348. function PhysicsImpostor(object, type, _options, _scene) {
  65349. if (_options === void 0) { _options = { mass: 0 }; }
  65350. var _this = this;
  65351. this.object = object;
  65352. this.type = type;
  65353. this._options = _options;
  65354. this._scene = _scene;
  65355. this._bodyUpdateRequired = false;
  65356. this._onBeforePhysicsStepCallbacks = new Array();
  65357. this._onAfterPhysicsStepCallbacks = new Array();
  65358. this._onPhysicsCollideCallbacks = [];
  65359. this._deltaPosition = BABYLON.Vector3.Zero();
  65360. this._isDisposed = false;
  65361. //temp variables for parent rotation calculations
  65362. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  65363. this._tmpQuat = new BABYLON.Quaternion();
  65364. this._tmpQuat2 = new BABYLON.Quaternion();
  65365. /**
  65366. * this function is executed by the physics engine.
  65367. */
  65368. this.beforeStep = function () {
  65369. if (!_this._physicsEngine) {
  65370. return;
  65371. }
  65372. _this.object.translate(_this._deltaPosition, -1);
  65373. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  65374. _this.object.computeWorldMatrix(false);
  65375. if (_this.object.parent && _this.object.rotationQuaternion) {
  65376. _this.getParentsRotation();
  65377. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  65378. }
  65379. else {
  65380. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  65381. }
  65382. if (!_this._options.disableBidirectionalTransformation) {
  65383. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  65384. }
  65385. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  65386. func(_this);
  65387. });
  65388. };
  65389. /**
  65390. * this function is executed by the physics engine.
  65391. */
  65392. this.afterStep = function () {
  65393. if (!_this._physicsEngine) {
  65394. return;
  65395. }
  65396. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  65397. func(_this);
  65398. });
  65399. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  65400. // object has now its world rotation. needs to be converted to local.
  65401. if (_this.object.parent && _this.object.rotationQuaternion) {
  65402. _this.getParentsRotation();
  65403. _this._tmpQuat.conjugateInPlace();
  65404. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  65405. }
  65406. // take the position set and make it the absolute position of this object.
  65407. _this.object.setAbsolutePosition(_this.object.position);
  65408. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  65409. _this.object.translate(_this._deltaPosition, 1);
  65410. };
  65411. /**
  65412. * Legacy collision detection event support
  65413. */
  65414. this.onCollideEvent = null;
  65415. //event and body object due to cannon's event-based architecture.
  65416. this.onCollide = function (e) {
  65417. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  65418. return;
  65419. }
  65420. if (!_this._physicsEngine) {
  65421. return;
  65422. }
  65423. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  65424. if (otherImpostor) {
  65425. // Legacy collision detection event support
  65426. if (_this.onCollideEvent) {
  65427. _this.onCollideEvent(_this, otherImpostor);
  65428. }
  65429. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  65430. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  65431. }).forEach(function (obj) {
  65432. obj.callback(_this, otherImpostor);
  65433. });
  65434. }
  65435. };
  65436. //sanity check!
  65437. if (!this.object) {
  65438. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  65439. return;
  65440. }
  65441. //legacy support for old syntax.
  65442. if (!this._scene && object.getScene) {
  65443. this._scene = object.getScene();
  65444. }
  65445. if (!this._scene) {
  65446. return;
  65447. }
  65448. this._physicsEngine = this._scene.getPhysicsEngine();
  65449. if (!this._physicsEngine) {
  65450. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  65451. }
  65452. else {
  65453. //set the object's quaternion, if not set
  65454. if (!this.object.rotationQuaternion) {
  65455. if (this.object.rotation) {
  65456. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  65457. }
  65458. else {
  65459. this.object.rotationQuaternion = new BABYLON.Quaternion();
  65460. }
  65461. }
  65462. //default options params
  65463. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  65464. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  65465. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  65466. this._joints = [];
  65467. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  65468. if (!this.object.parent || this._options.ignoreParent) {
  65469. this._init();
  65470. }
  65471. else if (this.object.parent.physicsImpostor) {
  65472. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  65473. }
  65474. }
  65475. }
  65476. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  65477. get: function () {
  65478. return this._isDisposed;
  65479. },
  65480. enumerable: true,
  65481. configurable: true
  65482. });
  65483. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  65484. get: function () {
  65485. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  65486. },
  65487. set: function (value) {
  65488. this.setMass(value);
  65489. },
  65490. enumerable: true,
  65491. configurable: true
  65492. });
  65493. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  65494. get: function () {
  65495. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  65496. },
  65497. set: function (value) {
  65498. if (!this._physicsEngine) {
  65499. return;
  65500. }
  65501. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  65502. },
  65503. enumerable: true,
  65504. configurable: true
  65505. });
  65506. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  65507. get: function () {
  65508. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  65509. },
  65510. set: function (value) {
  65511. if (!this._physicsEngine) {
  65512. return;
  65513. }
  65514. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  65515. },
  65516. enumerable: true,
  65517. configurable: true
  65518. });
  65519. /**
  65520. * This function will completly initialize this impostor.
  65521. * It will create a new body - but only if this mesh has no parent.
  65522. * If it has, this impostor will not be used other than to define the impostor
  65523. * of the child mesh.
  65524. */
  65525. PhysicsImpostor.prototype._init = function () {
  65526. if (!this._physicsEngine) {
  65527. return;
  65528. }
  65529. this._physicsEngine.removeImpostor(this);
  65530. this.physicsBody = null;
  65531. this._parent = this._parent || this._getPhysicsParent();
  65532. if (!this.parent || this._options.ignoreParent) {
  65533. this._physicsEngine.addImpostor(this);
  65534. }
  65535. };
  65536. PhysicsImpostor.prototype._getPhysicsParent = function () {
  65537. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  65538. var parentMesh = this.object.parent;
  65539. return parentMesh.physicsImpostor;
  65540. }
  65541. return null;
  65542. };
  65543. /**
  65544. * Should a new body be generated.
  65545. */
  65546. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  65547. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  65548. };
  65549. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  65550. this.forceUpdate();
  65551. };
  65552. /**
  65553. * Force a regeneration of this or the parent's impostor's body.
  65554. * Use under cautious - This will remove all joints already implemented.
  65555. */
  65556. PhysicsImpostor.prototype.forceUpdate = function () {
  65557. this._init();
  65558. if (this.parent && !this._options.ignoreParent) {
  65559. this.parent.forceUpdate();
  65560. }
  65561. };
  65562. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  65563. /*public get mesh(): AbstractMesh {
  65564. return this._mesh;
  65565. }*/
  65566. /**
  65567. * Gets the body that holds this impostor. Either its own, or its parent.
  65568. */
  65569. get: function () {
  65570. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  65571. },
  65572. /**
  65573. * Set the physics body. Used mainly by the physics engine/plugin
  65574. */
  65575. set: function (physicsBody) {
  65576. if (this._physicsBody && this._physicsEngine) {
  65577. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  65578. }
  65579. this._physicsBody = physicsBody;
  65580. this.resetUpdateFlags();
  65581. },
  65582. enumerable: true,
  65583. configurable: true
  65584. });
  65585. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  65586. get: function () {
  65587. return !this._options.ignoreParent && this._parent ? this._parent : null;
  65588. },
  65589. set: function (value) {
  65590. this._parent = value;
  65591. },
  65592. enumerable: true,
  65593. configurable: true
  65594. });
  65595. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  65596. this._bodyUpdateRequired = false;
  65597. };
  65598. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  65599. if (this.object.getBoundingInfo) {
  65600. var q = this.object.rotationQuaternion;
  65601. //reset rotation
  65602. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  65603. //calculate the world matrix with no rotation
  65604. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65605. var boundingInfo = this.object.getBoundingInfo();
  65606. var size = void 0;
  65607. if (boundingInfo) {
  65608. size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  65609. }
  65610. else {
  65611. size = BABYLON.Vector3.Zero();
  65612. }
  65613. //bring back the rotation
  65614. this.object.rotationQuaternion = q;
  65615. //calculate the world matrix with the new rotation
  65616. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  65617. return size;
  65618. }
  65619. else {
  65620. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  65621. }
  65622. };
  65623. PhysicsImpostor.prototype.getObjectCenter = function () {
  65624. if (this.object.getBoundingInfo) {
  65625. var boundingInfo = this.object.getBoundingInfo();
  65626. if (!boundingInfo) {
  65627. return this.object.position;
  65628. }
  65629. return boundingInfo.boundingBox.centerWorld;
  65630. }
  65631. else {
  65632. return this.object.position;
  65633. }
  65634. };
  65635. /**
  65636. * Get a specific parametes from the options parameter.
  65637. */
  65638. PhysicsImpostor.prototype.getParam = function (paramName) {
  65639. return this._options[paramName];
  65640. };
  65641. /**
  65642. * Sets a specific parameter in the options given to the physics plugin
  65643. */
  65644. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  65645. this._options[paramName] = value;
  65646. this._bodyUpdateRequired = true;
  65647. };
  65648. /**
  65649. * Specifically change the body's mass option. Won't recreate the physics body object
  65650. */
  65651. PhysicsImpostor.prototype.setMass = function (mass) {
  65652. if (this.getParam("mass") !== mass) {
  65653. this.setParam("mass", mass);
  65654. }
  65655. if (this._physicsEngine) {
  65656. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  65657. }
  65658. };
  65659. PhysicsImpostor.prototype.getLinearVelocity = function () {
  65660. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  65661. };
  65662. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  65663. if (this._physicsEngine) {
  65664. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  65665. }
  65666. };
  65667. PhysicsImpostor.prototype.getAngularVelocity = function () {
  65668. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  65669. };
  65670. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  65671. if (this._physicsEngine) {
  65672. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  65673. }
  65674. };
  65675. /**
  65676. * Execute a function with the physics plugin native code.
  65677. * Provide a function the will have two variables - the world object and the physics body object.
  65678. */
  65679. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  65680. if (this._physicsEngine) {
  65681. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  65682. }
  65683. };
  65684. /**
  65685. * Register a function that will be executed before the physics world is stepping forward.
  65686. */
  65687. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  65688. this._onBeforePhysicsStepCallbacks.push(func);
  65689. };
  65690. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  65691. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  65692. if (index > -1) {
  65693. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  65694. }
  65695. else {
  65696. BABYLON.Tools.Warn("Function to remove was not found");
  65697. }
  65698. };
  65699. /**
  65700. * Register a function that will be executed after the physics step
  65701. */
  65702. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  65703. this._onAfterPhysicsStepCallbacks.push(func);
  65704. };
  65705. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  65706. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  65707. if (index > -1) {
  65708. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  65709. }
  65710. else {
  65711. BABYLON.Tools.Warn("Function to remove was not found");
  65712. }
  65713. };
  65714. /**
  65715. * register a function that will be executed when this impostor collides against a different body.
  65716. */
  65717. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  65718. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65719. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  65720. };
  65721. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  65722. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  65723. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  65724. if (index > -1) {
  65725. this._onPhysicsCollideCallbacks.splice(index, 1);
  65726. }
  65727. else {
  65728. BABYLON.Tools.Warn("Function to remove was not found");
  65729. }
  65730. };
  65731. PhysicsImpostor.prototype.getParentsRotation = function () {
  65732. var parent = this.object.parent;
  65733. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  65734. while (parent) {
  65735. if (parent.rotationQuaternion) {
  65736. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  65737. }
  65738. else {
  65739. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  65740. }
  65741. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  65742. parent = parent.parent;
  65743. }
  65744. return this._tmpQuat;
  65745. };
  65746. /**
  65747. * Apply a force
  65748. */
  65749. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  65750. if (this._physicsEngine) {
  65751. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  65752. }
  65753. return this;
  65754. };
  65755. /**
  65756. * Apply an impulse
  65757. */
  65758. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  65759. if (this._physicsEngine) {
  65760. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  65761. }
  65762. return this;
  65763. };
  65764. /**
  65765. * A help function to create a joint.
  65766. */
  65767. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  65768. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  65769. this.addJoint(otherImpostor, joint);
  65770. return this;
  65771. };
  65772. /**
  65773. * Add a joint to this impostor with a different impostor.
  65774. */
  65775. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  65776. this._joints.push({
  65777. otherImpostor: otherImpostor,
  65778. joint: joint
  65779. });
  65780. if (this._physicsEngine) {
  65781. this._physicsEngine.addJoint(this, otherImpostor, joint);
  65782. }
  65783. return this;
  65784. };
  65785. /**
  65786. * Will keep this body still, in a sleep mode.
  65787. */
  65788. PhysicsImpostor.prototype.sleep = function () {
  65789. if (this._physicsEngine) {
  65790. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  65791. }
  65792. return this;
  65793. };
  65794. /**
  65795. * Wake the body up.
  65796. */
  65797. PhysicsImpostor.prototype.wakeUp = function () {
  65798. if (this._physicsEngine) {
  65799. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  65800. }
  65801. return this;
  65802. };
  65803. PhysicsImpostor.prototype.clone = function (newObject) {
  65804. if (!newObject)
  65805. return null;
  65806. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  65807. };
  65808. PhysicsImpostor.prototype.dispose = function () {
  65809. var _this = this;
  65810. //no dispose if no physics engine is available.
  65811. if (!this._physicsEngine) {
  65812. return;
  65813. }
  65814. this._joints.forEach(function (j) {
  65815. if (_this._physicsEngine) {
  65816. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  65817. }
  65818. });
  65819. //dispose the physics body
  65820. this._physicsEngine.removeImpostor(this);
  65821. if (this.parent) {
  65822. this.parent.forceUpdate();
  65823. }
  65824. else {
  65825. /*this._object.getChildMeshes().forEach(function(mesh) {
  65826. if (mesh.physicsImpostor) {
  65827. if (disposeChildren) {
  65828. mesh.physicsImpostor.dispose();
  65829. mesh.physicsImpostor = null;
  65830. }
  65831. }
  65832. })*/
  65833. }
  65834. this._isDisposed = true;
  65835. };
  65836. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  65837. this._deltaPosition.copyFrom(position);
  65838. };
  65839. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  65840. if (!this._deltaRotation) {
  65841. this._deltaRotation = new BABYLON.Quaternion();
  65842. }
  65843. this._deltaRotation.copyFrom(rotation);
  65844. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  65845. };
  65846. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  65847. if (this._physicsEngine) {
  65848. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  65849. }
  65850. return this;
  65851. };
  65852. PhysicsImpostor.prototype.getRadius = function () {
  65853. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  65854. };
  65855. /**
  65856. * Sync a bone with this impostor
  65857. * @param bone The bone to sync to the impostor.
  65858. * @param boneMesh The mesh that the bone is influencing.
  65859. * @param jointPivot The pivot of the joint / bone in local space.
  65860. * @param distToJoint Optional distance from the impostor to the joint.
  65861. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65862. */
  65863. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  65864. var tempVec = PhysicsImpostor._tmpVecs[0];
  65865. var mesh = this.object;
  65866. if (mesh.rotationQuaternion) {
  65867. if (adjustRotation) {
  65868. var tempQuat = PhysicsImpostor._tmpQuat;
  65869. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  65870. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  65871. }
  65872. else {
  65873. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  65874. }
  65875. }
  65876. tempVec.x = 0;
  65877. tempVec.y = 0;
  65878. tempVec.z = 0;
  65879. if (jointPivot) {
  65880. tempVec.x = jointPivot.x;
  65881. tempVec.y = jointPivot.y;
  65882. tempVec.z = jointPivot.z;
  65883. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  65884. if (distToJoint === undefined || distToJoint === null) {
  65885. distToJoint = jointPivot.length();
  65886. }
  65887. tempVec.x *= distToJoint;
  65888. tempVec.y *= distToJoint;
  65889. tempVec.z *= distToJoint;
  65890. }
  65891. if (bone.getParent()) {
  65892. tempVec.addInPlace(mesh.getAbsolutePosition());
  65893. bone.setAbsolutePosition(tempVec, boneMesh);
  65894. }
  65895. else {
  65896. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  65897. boneMesh.position.x -= tempVec.x;
  65898. boneMesh.position.y -= tempVec.y;
  65899. boneMesh.position.z -= tempVec.z;
  65900. }
  65901. };
  65902. /**
  65903. * Sync impostor to a bone
  65904. * @param bone The bone that the impostor will be synced to.
  65905. * @param boneMesh The mesh that the bone is influencing.
  65906. * @param jointPivot The pivot of the joint / bone in local space.
  65907. * @param distToJoint Optional distance from the impostor to the joint.
  65908. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  65909. * @param boneAxis Optional vector3 axis the bone is aligned with
  65910. */
  65911. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  65912. var mesh = this.object;
  65913. if (mesh.rotationQuaternion) {
  65914. if (adjustRotation) {
  65915. var tempQuat = PhysicsImpostor._tmpQuat;
  65916. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  65917. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  65918. }
  65919. else {
  65920. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  65921. }
  65922. }
  65923. var pos = PhysicsImpostor._tmpVecs[0];
  65924. var boneDir = PhysicsImpostor._tmpVecs[1];
  65925. if (!boneAxis) {
  65926. boneAxis = PhysicsImpostor._tmpVecs[2];
  65927. boneAxis.x = 0;
  65928. boneAxis.y = 1;
  65929. boneAxis.z = 0;
  65930. }
  65931. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  65932. bone.getAbsolutePositionToRef(boneMesh, pos);
  65933. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  65934. distToJoint = jointPivot.length();
  65935. }
  65936. if (distToJoint !== undefined && distToJoint !== null) {
  65937. pos.x += boneDir.x * distToJoint;
  65938. pos.y += boneDir.y * distToJoint;
  65939. pos.z += boneDir.z * distToJoint;
  65940. }
  65941. mesh.setAbsolutePosition(pos);
  65942. };
  65943. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  65944. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  65945. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  65946. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  65947. //Impostor types
  65948. PhysicsImpostor.NoImpostor = 0;
  65949. PhysicsImpostor.SphereImpostor = 1;
  65950. PhysicsImpostor.BoxImpostor = 2;
  65951. PhysicsImpostor.PlaneImpostor = 3;
  65952. PhysicsImpostor.MeshImpostor = 4;
  65953. PhysicsImpostor.CylinderImpostor = 7;
  65954. PhysicsImpostor.ParticleImpostor = 8;
  65955. PhysicsImpostor.HeightmapImpostor = 9;
  65956. return PhysicsImpostor;
  65957. }());
  65958. BABYLON.PhysicsImpostor = PhysicsImpostor;
  65959. })(BABYLON || (BABYLON = {}));
  65960. //# sourceMappingURL=babylon.physicsImpostor.js.map
  65961. var BABYLON;
  65962. (function (BABYLON) {
  65963. var PhysicsEngine = /** @class */ (function () {
  65964. function PhysicsEngine(gravity, _physicsPlugin) {
  65965. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  65966. this._physicsPlugin = _physicsPlugin;
  65967. //new methods and parameters
  65968. this._impostors = [];
  65969. this._joints = [];
  65970. if (!this._physicsPlugin.isSupported()) {
  65971. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  65972. + "Please make sure it is included.");
  65973. }
  65974. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  65975. this.setGravity(gravity);
  65976. this.setTimeStep();
  65977. }
  65978. PhysicsEngine.prototype.setGravity = function (gravity) {
  65979. this.gravity = gravity;
  65980. this._physicsPlugin.setGravity(this.gravity);
  65981. };
  65982. /**
  65983. * Set the time step of the physics engine.
  65984. * default is 1/60.
  65985. * To slow it down, enter 1/600 for example.
  65986. * To speed it up, 1/30
  65987. * @param {number} newTimeStep the new timestep to apply to this world.
  65988. */
  65989. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  65990. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  65991. this._physicsPlugin.setTimeStep(newTimeStep);
  65992. };
  65993. /**
  65994. * Get the time step of the physics engine.
  65995. */
  65996. PhysicsEngine.prototype.getTimeStep = function () {
  65997. return this._physicsPlugin.getTimeStep();
  65998. };
  65999. PhysicsEngine.prototype.dispose = function () {
  66000. this._impostors.forEach(function (impostor) {
  66001. impostor.dispose();
  66002. });
  66003. this._physicsPlugin.dispose();
  66004. };
  66005. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  66006. return this._physicsPlugin.name;
  66007. };
  66008. /**
  66009. * Adding a new impostor for the impostor tracking.
  66010. * This will be done by the impostor itself.
  66011. * @param {PhysicsImpostor} impostor the impostor to add
  66012. */
  66013. PhysicsEngine.prototype.addImpostor = function (impostor) {
  66014. impostor.uniqueId = this._impostors.push(impostor);
  66015. //if no parent, generate the body
  66016. if (!impostor.parent) {
  66017. this._physicsPlugin.generatePhysicsBody(impostor);
  66018. }
  66019. };
  66020. /**
  66021. * Remove an impostor from the engine.
  66022. * This impostor and its mesh will not longer be updated by the physics engine.
  66023. * @param {PhysicsImpostor} impostor the impostor to remove
  66024. */
  66025. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  66026. var index = this._impostors.indexOf(impostor);
  66027. if (index > -1) {
  66028. var removed = this._impostors.splice(index, 1);
  66029. //Is it needed?
  66030. if (removed.length) {
  66031. //this will also remove it from the world.
  66032. removed[0].physicsBody = null;
  66033. }
  66034. }
  66035. };
  66036. /**
  66037. * Add a joint to the physics engine
  66038. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  66039. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  66040. * @param {PhysicsJoint} the joint that will connect both impostors.
  66041. */
  66042. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  66043. var impostorJoint = {
  66044. mainImpostor: mainImpostor,
  66045. connectedImpostor: connectedImpostor,
  66046. joint: joint
  66047. };
  66048. joint.physicsPlugin = this._physicsPlugin;
  66049. this._joints.push(impostorJoint);
  66050. this._physicsPlugin.generateJoint(impostorJoint);
  66051. };
  66052. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  66053. var matchingJoints = this._joints.filter(function (impostorJoint) {
  66054. return (impostorJoint.connectedImpostor === connectedImpostor
  66055. && impostorJoint.joint === joint
  66056. && impostorJoint.mainImpostor === mainImpostor);
  66057. });
  66058. if (matchingJoints.length) {
  66059. this._physicsPlugin.removeJoint(matchingJoints[0]);
  66060. //TODO remove it from the list as well
  66061. }
  66062. };
  66063. /**
  66064. * Called by the scene. no need to call it.
  66065. */
  66066. PhysicsEngine.prototype._step = function (delta) {
  66067. var _this = this;
  66068. //check if any mesh has no body / requires an update
  66069. this._impostors.forEach(function (impostor) {
  66070. if (impostor.isBodyInitRequired()) {
  66071. _this._physicsPlugin.generatePhysicsBody(impostor);
  66072. }
  66073. });
  66074. if (delta > 0.1) {
  66075. delta = 0.1;
  66076. }
  66077. else if (delta <= 0) {
  66078. delta = 1.0 / 60.0;
  66079. }
  66080. this._physicsPlugin.executeStep(delta, this._impostors);
  66081. };
  66082. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  66083. return this._physicsPlugin;
  66084. };
  66085. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  66086. for (var i = 0; i < this._impostors.length; ++i) {
  66087. if (this._impostors[i].object === object) {
  66088. return this._impostors[i];
  66089. }
  66090. }
  66091. return null;
  66092. };
  66093. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  66094. for (var i = 0; i < this._impostors.length; ++i) {
  66095. if (this._impostors[i].physicsBody === body) {
  66096. return this._impostors[i];
  66097. }
  66098. }
  66099. return null;
  66100. };
  66101. // Statics
  66102. PhysicsEngine.Epsilon = 0.001;
  66103. return PhysicsEngine;
  66104. }());
  66105. BABYLON.PhysicsEngine = PhysicsEngine;
  66106. })(BABYLON || (BABYLON = {}));
  66107. //# sourceMappingURL=babylon.physicsEngine.js.map
  66108. var BABYLON;
  66109. (function (BABYLON) {
  66110. var CannonJSPlugin = /** @class */ (function () {
  66111. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  66112. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  66113. if (iterations === void 0) { iterations = 10; }
  66114. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  66115. this.name = "CannonJSPlugin";
  66116. this._physicsMaterials = new Array();
  66117. this._fixedTimeStep = 1 / 60;
  66118. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  66119. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  66120. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  66121. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  66122. this._tmpPosition = BABYLON.Vector3.Zero();
  66123. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  66124. this._tmpUnityRotation = new BABYLON.Quaternion();
  66125. if (!this.isSupported()) {
  66126. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  66127. return;
  66128. }
  66129. this.world = new this.BJSCANNON.World();
  66130. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  66131. this.world.solver.iterations = iterations;
  66132. }
  66133. CannonJSPlugin.prototype.setGravity = function (gravity) {
  66134. this.world.gravity.copy(gravity);
  66135. };
  66136. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  66137. this._fixedTimeStep = timeStep;
  66138. };
  66139. CannonJSPlugin.prototype.getTimeStep = function () {
  66140. return this._fixedTimeStep;
  66141. };
  66142. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  66143. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  66144. };
  66145. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66146. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66147. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66148. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  66149. };
  66150. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66151. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  66152. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  66153. impostor.physicsBody.applyForce(impulse, worldPoint);
  66154. };
  66155. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66156. //parent-child relationship. Does this impostor has a parent impostor?
  66157. if (impostor.parent) {
  66158. if (impostor.physicsBody) {
  66159. this.removePhysicsBody(impostor);
  66160. //TODO is that needed?
  66161. impostor.forceUpdate();
  66162. }
  66163. return;
  66164. }
  66165. //should a new body be created for this impostor?
  66166. if (impostor.isBodyInitRequired()) {
  66167. var shape = this._createShape(impostor);
  66168. //unregister events, if body is being changed
  66169. var oldBody = impostor.physicsBody;
  66170. if (oldBody) {
  66171. this.removePhysicsBody(impostor);
  66172. }
  66173. //create the body and material
  66174. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  66175. var bodyCreationObject = {
  66176. mass: impostor.getParam("mass"),
  66177. material: material
  66178. };
  66179. // A simple extend, in case native options were used.
  66180. var nativeOptions = impostor.getParam("nativeOptions");
  66181. for (var key in nativeOptions) {
  66182. if (nativeOptions.hasOwnProperty(key)) {
  66183. bodyCreationObject[key] = nativeOptions[key];
  66184. }
  66185. }
  66186. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  66187. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  66188. this.world.addEventListener("preStep", impostor.beforeStep);
  66189. this.world.addEventListener("postStep", impostor.afterStep);
  66190. impostor.physicsBody.addShape(shape);
  66191. this.world.add(impostor.physicsBody);
  66192. //try to keep the body moving in the right direction by taking old properties.
  66193. //Should be tested!
  66194. if (oldBody) {
  66195. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  66196. impostor.physicsBody[param].copy(oldBody[param]);
  66197. });
  66198. }
  66199. this._processChildMeshes(impostor);
  66200. }
  66201. //now update the body's transformation
  66202. this._updatePhysicsBodyTransformation(impostor);
  66203. };
  66204. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  66205. var _this = this;
  66206. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  66207. var currentRotation = mainImpostor.object.rotationQuaternion;
  66208. if (meshChildren.length) {
  66209. var processMesh = function (localPosition, mesh) {
  66210. if (!currentRotation || !mesh.rotationQuaternion) {
  66211. return;
  66212. }
  66213. var childImpostor = mesh.getPhysicsImpostor();
  66214. if (childImpostor) {
  66215. var parent = childImpostor.parent;
  66216. if (parent !== mainImpostor) {
  66217. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  66218. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  66219. if (childImpostor.physicsBody) {
  66220. _this.removePhysicsBody(childImpostor);
  66221. childImpostor.physicsBody = null;
  66222. }
  66223. childImpostor.parent = mainImpostor;
  66224. childImpostor.resetUpdateFlags();
  66225. 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));
  66226. //Add the mass of the children.
  66227. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  66228. }
  66229. }
  66230. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  66231. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  66232. };
  66233. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  66234. }
  66235. };
  66236. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66237. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  66238. this.world.removeEventListener("preStep", impostor.beforeStep);
  66239. this.world.removeEventListener("postStep", impostor.afterStep);
  66240. this.world.remove(impostor.physicsBody);
  66241. };
  66242. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66243. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66244. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66245. if (!mainBody || !connectedBody) {
  66246. return;
  66247. }
  66248. var constraint;
  66249. var jointData = impostorJoint.joint.jointData;
  66250. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  66251. var constraintData = {
  66252. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  66253. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  66254. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  66255. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  66256. maxForce: jointData.nativeParams.maxForce,
  66257. collideConnected: !!jointData.collision
  66258. };
  66259. switch (impostorJoint.joint.type) {
  66260. case BABYLON.PhysicsJoint.HingeJoint:
  66261. case BABYLON.PhysicsJoint.Hinge2Joint:
  66262. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  66263. break;
  66264. case BABYLON.PhysicsJoint.DistanceJoint:
  66265. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  66266. break;
  66267. case BABYLON.PhysicsJoint.SpringJoint:
  66268. var springData = jointData;
  66269. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  66270. restLength: springData.length,
  66271. stiffness: springData.stiffness,
  66272. damping: springData.damping,
  66273. localAnchorA: constraintData.pivotA,
  66274. localAnchorB: constraintData.pivotB
  66275. });
  66276. break;
  66277. case BABYLON.PhysicsJoint.LockJoint:
  66278. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  66279. break;
  66280. case BABYLON.PhysicsJoint.PointToPointJoint:
  66281. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66282. default:
  66283. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  66284. break;
  66285. }
  66286. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  66287. constraint.collideConnected = !!jointData.collision;
  66288. impostorJoint.joint.physicsJoint = constraint;
  66289. //don't add spring as constraint, as it is not one.
  66290. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  66291. this.world.addConstraint(constraint);
  66292. }
  66293. else {
  66294. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  66295. constraint.applyForce();
  66296. });
  66297. }
  66298. };
  66299. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66300. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  66301. };
  66302. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  66303. var index;
  66304. var mat;
  66305. for (index = 0; index < this._physicsMaterials.length; index++) {
  66306. mat = this._physicsMaterials[index];
  66307. if (mat.friction === friction && mat.restitution === restitution) {
  66308. return mat;
  66309. }
  66310. }
  66311. var currentMat = new this.BJSCANNON.Material(name);
  66312. currentMat.friction = friction;
  66313. currentMat.restitution = restitution;
  66314. this._physicsMaterials.push(currentMat);
  66315. return currentMat;
  66316. };
  66317. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  66318. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  66319. };
  66320. CannonJSPlugin.prototype._createShape = function (impostor) {
  66321. var object = impostor.object;
  66322. var returnValue;
  66323. var extendSize = impostor.getObjectExtendSize();
  66324. switch (impostor.type) {
  66325. case BABYLON.PhysicsImpostor.SphereImpostor:
  66326. var radiusX = extendSize.x;
  66327. var radiusY = extendSize.y;
  66328. var radiusZ = extendSize.z;
  66329. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  66330. break;
  66331. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  66332. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66333. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  66334. break;
  66335. case BABYLON.PhysicsImpostor.BoxImpostor:
  66336. var box = extendSize.scale(0.5);
  66337. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  66338. break;
  66339. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66340. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  66341. returnValue = new this.BJSCANNON.Plane();
  66342. break;
  66343. case BABYLON.PhysicsImpostor.MeshImpostor:
  66344. // should transform the vertex data to world coordinates!!
  66345. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  66346. var rawFaces = object.getIndices ? object.getIndices() : [];
  66347. if (!rawVerts)
  66348. return;
  66349. // get only scale! so the object could transform correctly.
  66350. var oldPosition = object.position.clone();
  66351. var oldRotation = object.rotation && object.rotation.clone();
  66352. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  66353. object.position.copyFromFloats(0, 0, 0);
  66354. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66355. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66356. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66357. var transform = object.computeWorldMatrix(true);
  66358. // convert rawVerts to object space
  66359. var temp = new Array();
  66360. var index;
  66361. for (index = 0; index < rawVerts.length; index += 3) {
  66362. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  66363. }
  66364. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  66365. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  66366. //now set back the transformation!
  66367. object.position.copyFrom(oldPosition);
  66368. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  66369. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  66370. break;
  66371. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  66372. var oldPosition2 = object.position.clone();
  66373. var oldRotation2 = object.rotation && object.rotation.clone();
  66374. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  66375. object.position.copyFromFloats(0, 0, 0);
  66376. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  66377. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  66378. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  66379. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  66380. returnValue = this._createHeightmap(object);
  66381. object.position.copyFrom(oldPosition2);
  66382. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  66383. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  66384. object.computeWorldMatrix(true);
  66385. break;
  66386. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66387. returnValue = new this.BJSCANNON.Particle();
  66388. break;
  66389. }
  66390. return returnValue;
  66391. };
  66392. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  66393. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  66394. var transform = object.computeWorldMatrix(true);
  66395. // convert rawVerts to object space
  66396. var temp = new Array();
  66397. var index;
  66398. for (index = 0; index < pos.length; index += 3) {
  66399. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  66400. }
  66401. pos = temp;
  66402. var matrix = new Array();
  66403. //For now pointDepth will not be used and will be automatically calculated.
  66404. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  66405. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  66406. var boundingInfo = (object.getBoundingInfo());
  66407. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  66408. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  66409. var elementSize = dim * 2 / arraySize;
  66410. for (var i = 0; i < pos.length; i = i + 3) {
  66411. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  66412. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  66413. var y = -pos[i + 2] + minY;
  66414. if (!matrix[x]) {
  66415. matrix[x] = [];
  66416. }
  66417. if (!matrix[x][z]) {
  66418. matrix[x][z] = y;
  66419. }
  66420. matrix[x][z] = Math.max(y, matrix[x][z]);
  66421. }
  66422. for (var x = 0; x <= arraySize; ++x) {
  66423. if (!matrix[x]) {
  66424. var loc = 1;
  66425. while (!matrix[(x + loc) % arraySize]) {
  66426. loc++;
  66427. }
  66428. matrix[x] = matrix[(x + loc) % arraySize].slice();
  66429. //console.log("missing x", x);
  66430. }
  66431. for (var z = 0; z <= arraySize; ++z) {
  66432. if (!matrix[x][z]) {
  66433. var loc = 1;
  66434. var newValue;
  66435. while (newValue === undefined) {
  66436. newValue = matrix[x][(z + loc++) % arraySize];
  66437. }
  66438. matrix[x][z] = newValue;
  66439. }
  66440. }
  66441. }
  66442. var shape = new this.BJSCANNON.Heightfield(matrix, {
  66443. elementSize: elementSize
  66444. });
  66445. //For future reference, needed for body transformation
  66446. shape.minY = minY;
  66447. return shape;
  66448. };
  66449. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  66450. var object = impostor.object;
  66451. //make sure it is updated...
  66452. object.computeWorldMatrix && object.computeWorldMatrix(true);
  66453. // The delta between the mesh position and the mesh bounding box center
  66454. var bInfo = object.getBoundingInfo();
  66455. if (!bInfo)
  66456. return;
  66457. var center = impostor.getObjectCenter();
  66458. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  66459. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  66460. this._tmpPosition.copyFrom(center);
  66461. var quaternion = object.rotationQuaternion;
  66462. if (!quaternion) {
  66463. return;
  66464. }
  66465. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  66466. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  66467. //-90 DEG in X, precalculated
  66468. quaternion = quaternion.multiply(this._minus90X);
  66469. //Invert! (Precalculated, 90 deg in X)
  66470. //No need to clone. this will never change.
  66471. impostor.setDeltaRotation(this._plus90X);
  66472. }
  66473. //If it is a heightfield, if should be centered.
  66474. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  66475. var mesh = object;
  66476. var boundingInfo = mesh.getBoundingInfo();
  66477. //calculate the correct body position:
  66478. var rotationQuaternion = mesh.rotationQuaternion;
  66479. mesh.rotationQuaternion = this._tmpUnityRotation;
  66480. mesh.computeWorldMatrix(true);
  66481. //get original center with no rotation
  66482. var c = center.clone();
  66483. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  66484. //rotation is back
  66485. mesh.rotationQuaternion = rotationQuaternion;
  66486. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  66487. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  66488. mesh.setPivotMatrix(p);
  66489. mesh.computeWorldMatrix(true);
  66490. //calculate the translation
  66491. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  66492. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  66493. //add it inverted to the delta
  66494. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  66495. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  66496. mesh.setPivotMatrix(oldPivot);
  66497. mesh.computeWorldMatrix(true);
  66498. }
  66499. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  66500. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  66501. //this._tmpPosition.copyFrom(object.position);
  66502. }
  66503. impostor.setDeltaPosition(this._tmpDeltaPosition);
  66504. //Now update the impostor object
  66505. impostor.physicsBody.position.copy(this._tmpPosition);
  66506. impostor.physicsBody.quaternion.copy(quaternion);
  66507. };
  66508. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66509. impostor.object.position.copyFrom(impostor.physicsBody.position);
  66510. if (impostor.object.rotationQuaternion) {
  66511. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  66512. }
  66513. };
  66514. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66515. impostor.physicsBody.position.copy(newPosition);
  66516. impostor.physicsBody.quaternion.copy(newRotation);
  66517. };
  66518. CannonJSPlugin.prototype.isSupported = function () {
  66519. return this.BJSCANNON !== undefined;
  66520. };
  66521. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66522. impostor.physicsBody.velocity.copy(velocity);
  66523. };
  66524. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66525. impostor.physicsBody.angularVelocity.copy(velocity);
  66526. };
  66527. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66528. var v = impostor.physicsBody.velocity;
  66529. if (!v) {
  66530. return null;
  66531. }
  66532. return new BABYLON.Vector3(v.x, v.y, v.z);
  66533. };
  66534. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66535. var v = impostor.physicsBody.angularVelocity;
  66536. if (!v) {
  66537. return null;
  66538. }
  66539. return new BABYLON.Vector3(v.x, v.y, v.z);
  66540. };
  66541. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66542. impostor.physicsBody.mass = mass;
  66543. impostor.physicsBody.updateMassProperties();
  66544. };
  66545. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  66546. return impostor.physicsBody.mass;
  66547. };
  66548. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  66549. return impostor.physicsBody.material.friction;
  66550. };
  66551. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66552. impostor.physicsBody.material.friction = friction;
  66553. };
  66554. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66555. return impostor.physicsBody.material.restitution;
  66556. };
  66557. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66558. impostor.physicsBody.material.restitution = restitution;
  66559. };
  66560. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  66561. impostor.physicsBody.sleep();
  66562. };
  66563. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  66564. impostor.physicsBody.wakeUp();
  66565. };
  66566. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66567. joint.physicsJoint.distance = maxDistance;
  66568. };
  66569. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66570. // if (!motorIndex) {
  66571. // joint.physicsJoint.enableMotor();
  66572. // }
  66573. // }
  66574. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  66575. // if (!motorIndex) {
  66576. // joint.physicsJoint.disableMotor();
  66577. // }
  66578. // }
  66579. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66580. if (!motorIndex) {
  66581. joint.physicsJoint.enableMotor();
  66582. joint.physicsJoint.setMotorSpeed(speed);
  66583. if (maxForce) {
  66584. this.setLimit(joint, maxForce);
  66585. }
  66586. }
  66587. };
  66588. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  66589. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  66590. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  66591. };
  66592. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66593. var body = impostor.physicsBody;
  66594. mesh.position.x = body.position.x;
  66595. mesh.position.y = body.position.y;
  66596. mesh.position.z = body.position.z;
  66597. if (mesh.rotationQuaternion) {
  66598. mesh.rotationQuaternion.x = body.quaternion.x;
  66599. mesh.rotationQuaternion.y = body.quaternion.y;
  66600. mesh.rotationQuaternion.z = body.quaternion.z;
  66601. mesh.rotationQuaternion.w = body.quaternion.w;
  66602. }
  66603. };
  66604. CannonJSPlugin.prototype.getRadius = function (impostor) {
  66605. var shape = impostor.physicsBody.shapes[0];
  66606. return shape.boundingSphereRadius;
  66607. };
  66608. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66609. var shape = impostor.physicsBody.shapes[0];
  66610. result.x = shape.halfExtents.x * 2;
  66611. result.y = shape.halfExtents.y * 2;
  66612. result.z = shape.halfExtents.z * 2;
  66613. };
  66614. CannonJSPlugin.prototype.dispose = function () {
  66615. };
  66616. return CannonJSPlugin;
  66617. }());
  66618. BABYLON.CannonJSPlugin = CannonJSPlugin;
  66619. })(BABYLON || (BABYLON = {}));
  66620. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  66621. var BABYLON;
  66622. (function (BABYLON) {
  66623. var OimoJSPlugin = /** @class */ (function () {
  66624. function OimoJSPlugin(iterations) {
  66625. this.name = "OimoJSPlugin";
  66626. this._tmpImpostorsArray = [];
  66627. this._tmpPositionVector = BABYLON.Vector3.Zero();
  66628. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  66629. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  66630. this.world.worldscale(1);
  66631. this.world.clear();
  66632. //making sure no stats are calculated
  66633. this.world.isNoStat = true;
  66634. }
  66635. OimoJSPlugin.prototype.setGravity = function (gravity) {
  66636. this.world.gravity.copy(gravity);
  66637. };
  66638. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  66639. this.world.timeStep = timeStep;
  66640. };
  66641. OimoJSPlugin.prototype.getTimeStep = function () {
  66642. return this.world.timeStep;
  66643. };
  66644. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  66645. var _this = this;
  66646. impostors.forEach(function (impostor) {
  66647. impostor.beforeStep();
  66648. });
  66649. this.world.step();
  66650. impostors.forEach(function (impostor) {
  66651. impostor.afterStep();
  66652. //update the ordered impostors array
  66653. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  66654. });
  66655. //check for collisions
  66656. var contact = this.world.contacts;
  66657. while (contact !== null) {
  66658. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  66659. contact = contact.next;
  66660. continue;
  66661. }
  66662. //is this body colliding with any other? get the impostor
  66663. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  66664. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  66665. if (!mainImpostor || !collidingImpostor) {
  66666. contact = contact.next;
  66667. continue;
  66668. }
  66669. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  66670. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  66671. contact = contact.next;
  66672. }
  66673. };
  66674. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  66675. var mass = impostor.physicsBody.massInfo.mass;
  66676. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  66677. };
  66678. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  66679. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  66680. this.applyImpulse(impostor, force, contactPoint);
  66681. };
  66682. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  66683. var _this = this;
  66684. //parent-child relationship. Does this impostor has a parent impostor?
  66685. if (impostor.parent) {
  66686. if (impostor.physicsBody) {
  66687. this.removePhysicsBody(impostor);
  66688. //TODO is that needed?
  66689. impostor.forceUpdate();
  66690. }
  66691. return;
  66692. }
  66693. if (impostor.isBodyInitRequired()) {
  66694. var bodyConfig = {
  66695. name: impostor.uniqueId,
  66696. //Oimo must have mass, also for static objects.
  66697. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  66698. size: [],
  66699. type: [],
  66700. pos: [],
  66701. rot: [],
  66702. move: impostor.getParam("mass") !== 0,
  66703. //Supporting older versions of Oimo
  66704. world: this.world
  66705. };
  66706. var impostors = [impostor];
  66707. var addToArray = function (parent) {
  66708. if (!parent.getChildMeshes)
  66709. return;
  66710. parent.getChildMeshes().forEach(function (m) {
  66711. if (m.physicsImpostor) {
  66712. impostors.push(m.physicsImpostor);
  66713. //m.physicsImpostor._init();
  66714. }
  66715. });
  66716. };
  66717. addToArray(impostor.object);
  66718. var checkWithEpsilon_1 = function (value) {
  66719. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  66720. };
  66721. impostors.forEach(function (i) {
  66722. if (!impostor.object.rotationQuaternion) {
  66723. return;
  66724. }
  66725. //get the correct bounding box
  66726. var oldQuaternion = i.object.rotationQuaternion;
  66727. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  66728. x: impostor.object.rotationQuaternion.x,
  66729. y: impostor.object.rotationQuaternion.y,
  66730. z: impostor.object.rotationQuaternion.z,
  66731. s: impostor.object.rotationQuaternion.w
  66732. });
  66733. var extendSize = i.getObjectExtendSize();
  66734. if (i === impostor) {
  66735. var center = impostor.getObjectCenter();
  66736. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  66737. //Can also use Array.prototype.push.apply
  66738. bodyConfig.pos.push(center.x);
  66739. bodyConfig.pos.push(center.y);
  66740. bodyConfig.pos.push(center.z);
  66741. //tmp solution
  66742. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66743. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66744. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  66745. }
  66746. else {
  66747. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  66748. bodyConfig.pos.push(localPosition.x);
  66749. bodyConfig.pos.push(localPosition.y);
  66750. bodyConfig.pos.push(localPosition.z);
  66751. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  66752. bodyConfig.rot.push(0);
  66753. bodyConfig.rot.push(0);
  66754. bodyConfig.rot.push(0);
  66755. }
  66756. // register mesh
  66757. switch (i.type) {
  66758. case BABYLON.PhysicsImpostor.ParticleImpostor:
  66759. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  66760. case BABYLON.PhysicsImpostor.SphereImpostor:
  66761. var radiusX = extendSize.x;
  66762. var radiusY = extendSize.y;
  66763. var radiusZ = extendSize.z;
  66764. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  66765. bodyConfig.type.push('sphere');
  66766. //due to the way oimo works with compounds, add 3 times
  66767. bodyConfig.size.push(size);
  66768. bodyConfig.size.push(size);
  66769. bodyConfig.size.push(size);
  66770. break;
  66771. case BABYLON.PhysicsImpostor.CylinderImpostor:
  66772. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  66773. var sizeY = checkWithEpsilon_1(extendSize.y);
  66774. bodyConfig.type.push('cylinder');
  66775. bodyConfig.size.push(sizeX);
  66776. bodyConfig.size.push(sizeY);
  66777. //due to the way oimo works with compounds, add one more value.
  66778. bodyConfig.size.push(sizeY);
  66779. break;
  66780. case BABYLON.PhysicsImpostor.PlaneImpostor:
  66781. case BABYLON.PhysicsImpostor.BoxImpostor:
  66782. default:
  66783. var sizeX = checkWithEpsilon_1(extendSize.x);
  66784. var sizeY = checkWithEpsilon_1(extendSize.y);
  66785. var sizeZ = checkWithEpsilon_1(extendSize.z);
  66786. bodyConfig.type.push('box');
  66787. bodyConfig.size.push(sizeX);
  66788. bodyConfig.size.push(sizeY);
  66789. bodyConfig.size.push(sizeZ);
  66790. break;
  66791. }
  66792. //actually not needed, but hey...
  66793. i.object.rotationQuaternion = oldQuaternion;
  66794. });
  66795. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  66796. }
  66797. else {
  66798. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  66799. }
  66800. impostor.setDeltaPosition(this._tmpPositionVector);
  66801. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  66802. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  66803. };
  66804. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  66805. //impostor.physicsBody.dispose();
  66806. //Same as : (older oimo versions)
  66807. this.world.removeRigidBody(impostor.physicsBody);
  66808. };
  66809. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  66810. var mainBody = impostorJoint.mainImpostor.physicsBody;
  66811. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  66812. if (!mainBody || !connectedBody) {
  66813. return;
  66814. }
  66815. var jointData = impostorJoint.joint.jointData;
  66816. var options = jointData.nativeParams || {};
  66817. var type;
  66818. var nativeJointData = {
  66819. body1: mainBody,
  66820. body2: connectedBody,
  66821. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  66822. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  66823. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  66824. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  66825. min: options.min,
  66826. max: options.max,
  66827. collision: options.collision || jointData.collision,
  66828. spring: options.spring,
  66829. //supporting older version of Oimo
  66830. world: this.world
  66831. };
  66832. switch (impostorJoint.joint.type) {
  66833. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  66834. type = "jointBall";
  66835. break;
  66836. case BABYLON.PhysicsJoint.SpringJoint:
  66837. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  66838. var springData = jointData;
  66839. nativeJointData.min = springData.length || nativeJointData.min;
  66840. //Max should also be set, just make sure it is at least min
  66841. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  66842. case BABYLON.PhysicsJoint.DistanceJoint:
  66843. type = "jointDistance";
  66844. nativeJointData.max = jointData.maxDistance;
  66845. break;
  66846. case BABYLON.PhysicsJoint.PrismaticJoint:
  66847. type = "jointPrisme";
  66848. break;
  66849. case BABYLON.PhysicsJoint.SliderJoint:
  66850. type = "jointSlide";
  66851. break;
  66852. case BABYLON.PhysicsJoint.WheelJoint:
  66853. type = "jointWheel";
  66854. break;
  66855. case BABYLON.PhysicsJoint.HingeJoint:
  66856. default:
  66857. type = "jointHinge";
  66858. break;
  66859. }
  66860. nativeJointData.type = type;
  66861. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  66862. };
  66863. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  66864. //Bug in Oimo prevents us from disposing a joint in the playground
  66865. //joint.joint.physicsJoint.dispose();
  66866. //So we will bruteforce it!
  66867. try {
  66868. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  66869. }
  66870. catch (e) {
  66871. BABYLON.Tools.Warn(e);
  66872. }
  66873. };
  66874. OimoJSPlugin.prototype.isSupported = function () {
  66875. return this.BJSOIMO !== undefined;
  66876. };
  66877. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  66878. if (!impostor.physicsBody.sleeping) {
  66879. //TODO check that
  66880. if (impostor.physicsBody.shapes.next) {
  66881. var parentShape = this._getLastShape(impostor.physicsBody);
  66882. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  66883. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  66884. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  66885. }
  66886. else {
  66887. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  66888. }
  66889. if (impostor.object.rotationQuaternion) {
  66890. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  66891. impostor.object.rotationQuaternion.normalize();
  66892. }
  66893. }
  66894. };
  66895. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  66896. var body = impostor.physicsBody;
  66897. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  66898. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  66899. body.syncShapes();
  66900. body.awake();
  66901. };
  66902. OimoJSPlugin.prototype._getLastShape = function (body) {
  66903. var lastShape = body.shapes;
  66904. while (lastShape.next) {
  66905. lastShape = lastShape.next;
  66906. }
  66907. return lastShape;
  66908. };
  66909. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  66910. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  66911. };
  66912. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  66913. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  66914. };
  66915. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  66916. var v = impostor.physicsBody.linearVelocity;
  66917. if (!v) {
  66918. return null;
  66919. }
  66920. return new BABYLON.Vector3(v.x, v.y, v.z);
  66921. };
  66922. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  66923. var v = impostor.physicsBody.angularVelocity;
  66924. if (!v) {
  66925. return null;
  66926. }
  66927. return new BABYLON.Vector3(v.x, v.y, v.z);
  66928. };
  66929. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  66930. var staticBody = mass === 0;
  66931. //this will actually set the body's density and not its mass.
  66932. //But this is how oimo treats the mass variable.
  66933. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  66934. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  66935. };
  66936. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  66937. return impostor.physicsBody.shapes.density;
  66938. };
  66939. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  66940. return impostor.physicsBody.shapes.friction;
  66941. };
  66942. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  66943. impostor.physicsBody.shapes.friction = friction;
  66944. };
  66945. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  66946. return impostor.physicsBody.shapes.restitution;
  66947. };
  66948. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  66949. impostor.physicsBody.shapes.restitution = restitution;
  66950. };
  66951. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  66952. impostor.physicsBody.sleep();
  66953. };
  66954. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  66955. impostor.physicsBody.awake();
  66956. };
  66957. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  66958. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  66959. if (minDistance !== void 0) {
  66960. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  66961. }
  66962. };
  66963. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  66964. //TODO separate rotational and transational motors.
  66965. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66966. if (motor) {
  66967. motor.setMotor(speed, maxForce);
  66968. }
  66969. };
  66970. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  66971. //TODO separate rotational and transational motors.
  66972. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  66973. if (motor) {
  66974. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  66975. }
  66976. };
  66977. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  66978. var body = impostor.physicsBody;
  66979. mesh.position.x = body.position.x;
  66980. mesh.position.y = body.position.y;
  66981. mesh.position.z = body.position.z;
  66982. if (mesh.rotationQuaternion) {
  66983. mesh.rotationQuaternion.x = body.orientation.x;
  66984. mesh.rotationQuaternion.y = body.orientation.y;
  66985. mesh.rotationQuaternion.z = body.orientation.z;
  66986. mesh.rotationQuaternion.w = body.orientation.s;
  66987. }
  66988. };
  66989. OimoJSPlugin.prototype.getRadius = function (impostor) {
  66990. return impostor.physicsBody.shapes.radius;
  66991. };
  66992. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  66993. var shape = impostor.physicsBody.shapes;
  66994. result.x = shape.halfWidth * 2;
  66995. result.y = shape.halfHeight * 2;
  66996. result.z = shape.halfDepth * 2;
  66997. };
  66998. OimoJSPlugin.prototype.dispose = function () {
  66999. this.world.clear();
  67000. };
  67001. return OimoJSPlugin;
  67002. }());
  67003. BABYLON.OimoJSPlugin = OimoJSPlugin;
  67004. })(BABYLON || (BABYLON = {}));
  67005. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  67006. var BABYLON;
  67007. (function (BABYLON) {
  67008. var Internals;
  67009. (function (Internals) {
  67010. /*
  67011. * Based on jsTGALoader - Javascript loader for TGA file
  67012. * By Vincent Thibault
  67013. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  67014. */
  67015. var TGATools = /** @class */ (function () {
  67016. function TGATools() {
  67017. }
  67018. TGATools.GetTGAHeader = function (data) {
  67019. var offset = 0;
  67020. var header = {
  67021. id_length: data[offset++],
  67022. colormap_type: data[offset++],
  67023. image_type: data[offset++],
  67024. colormap_index: data[offset++] | data[offset++] << 8,
  67025. colormap_length: data[offset++] | data[offset++] << 8,
  67026. colormap_size: data[offset++],
  67027. origin: [
  67028. data[offset++] | data[offset++] << 8,
  67029. data[offset++] | data[offset++] << 8
  67030. ],
  67031. width: data[offset++] | data[offset++] << 8,
  67032. height: data[offset++] | data[offset++] << 8,
  67033. pixel_size: data[offset++],
  67034. flags: data[offset++]
  67035. };
  67036. return header;
  67037. };
  67038. TGATools.UploadContent = function (gl, data) {
  67039. // Not enough data to contain header ?
  67040. if (data.length < 19) {
  67041. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  67042. return;
  67043. }
  67044. // Read Header
  67045. var offset = 18;
  67046. var header = TGATools.GetTGAHeader(data);
  67047. // Assume it's a valid Targa file.
  67048. if (header.id_length + offset > data.length) {
  67049. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  67050. return;
  67051. }
  67052. // Skip not needed data
  67053. offset += header.id_length;
  67054. var use_rle = false;
  67055. var use_pal = false;
  67056. var use_rgb = false;
  67057. var use_grey = false;
  67058. // Get some informations.
  67059. switch (header.image_type) {
  67060. case TGATools._TYPE_RLE_INDEXED:
  67061. use_rle = true;
  67062. case TGATools._TYPE_INDEXED:
  67063. use_pal = true;
  67064. break;
  67065. case TGATools._TYPE_RLE_RGB:
  67066. use_rle = true;
  67067. case TGATools._TYPE_RGB:
  67068. use_rgb = true;
  67069. break;
  67070. case TGATools._TYPE_RLE_GREY:
  67071. use_rle = true;
  67072. case TGATools._TYPE_GREY:
  67073. use_grey = true;
  67074. break;
  67075. }
  67076. var pixel_data;
  67077. // var numAlphaBits = header.flags & 0xf;
  67078. var pixel_size = header.pixel_size >> 3;
  67079. var pixel_total = header.width * header.height * pixel_size;
  67080. // Read palettes
  67081. var palettes;
  67082. if (use_pal) {
  67083. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  67084. }
  67085. // Read LRE
  67086. if (use_rle) {
  67087. pixel_data = new Uint8Array(pixel_total);
  67088. var c, count, i;
  67089. var localOffset = 0;
  67090. var pixels = new Uint8Array(pixel_size);
  67091. while (offset < pixel_total && localOffset < pixel_total) {
  67092. c = data[offset++];
  67093. count = (c & 0x7f) + 1;
  67094. // RLE pixels
  67095. if (c & 0x80) {
  67096. // Bind pixel tmp array
  67097. for (i = 0; i < pixel_size; ++i) {
  67098. pixels[i] = data[offset++];
  67099. }
  67100. // Copy pixel array
  67101. for (i = 0; i < count; ++i) {
  67102. pixel_data.set(pixels, localOffset + i * pixel_size);
  67103. }
  67104. localOffset += pixel_size * count;
  67105. }
  67106. else {
  67107. count *= pixel_size;
  67108. for (i = 0; i < count; ++i) {
  67109. pixel_data[localOffset + i] = data[offset++];
  67110. }
  67111. localOffset += count;
  67112. }
  67113. }
  67114. }
  67115. else {
  67116. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  67117. }
  67118. // Load to texture
  67119. var x_start, y_start, x_step, y_step, y_end, x_end;
  67120. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  67121. default:
  67122. case TGATools._ORIGIN_UL:
  67123. x_start = 0;
  67124. x_step = 1;
  67125. x_end = header.width;
  67126. y_start = 0;
  67127. y_step = 1;
  67128. y_end = header.height;
  67129. break;
  67130. case TGATools._ORIGIN_BL:
  67131. x_start = 0;
  67132. x_step = 1;
  67133. x_end = header.width;
  67134. y_start = header.height - 1;
  67135. y_step = -1;
  67136. y_end = -1;
  67137. break;
  67138. case TGATools._ORIGIN_UR:
  67139. x_start = header.width - 1;
  67140. x_step = -1;
  67141. x_end = -1;
  67142. y_start = 0;
  67143. y_step = 1;
  67144. y_end = header.height;
  67145. break;
  67146. case TGATools._ORIGIN_BR:
  67147. x_start = header.width - 1;
  67148. x_step = -1;
  67149. x_end = -1;
  67150. y_start = header.height - 1;
  67151. y_step = -1;
  67152. y_end = -1;
  67153. break;
  67154. }
  67155. // Load the specify method
  67156. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  67157. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  67158. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  67159. };
  67160. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67161. var image = pixel_data, colormap = palettes;
  67162. var width = header.width, height = header.height;
  67163. var color, i = 0, x, y;
  67164. var imageData = new Uint8Array(width * height * 4);
  67165. for (y = y_start; y !== y_end; y += y_step) {
  67166. for (x = x_start; x !== x_end; x += x_step, i++) {
  67167. color = image[i];
  67168. imageData[(x + width * y) * 4 + 3] = 255;
  67169. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  67170. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  67171. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  67172. }
  67173. }
  67174. return imageData;
  67175. };
  67176. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67177. var image = pixel_data;
  67178. var width = header.width, height = header.height;
  67179. var color, i = 0, x, y;
  67180. var imageData = new Uint8Array(width * height * 4);
  67181. for (y = y_start; y !== y_end; y += y_step) {
  67182. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67183. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  67184. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  67185. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  67186. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  67187. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  67188. }
  67189. }
  67190. return imageData;
  67191. };
  67192. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67193. var image = pixel_data;
  67194. var width = header.width, height = header.height;
  67195. var i = 0, x, y;
  67196. var imageData = new Uint8Array(width * height * 4);
  67197. for (y = y_start; y !== y_end; y += y_step) {
  67198. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  67199. imageData[(x + width * y) * 4 + 3] = 255;
  67200. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67201. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67202. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67203. }
  67204. }
  67205. return imageData;
  67206. };
  67207. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67208. var image = pixel_data;
  67209. var width = header.width, height = header.height;
  67210. var i = 0, x, y;
  67211. var imageData = new Uint8Array(width * height * 4);
  67212. for (y = y_start; y !== y_end; y += y_step) {
  67213. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  67214. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67215. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  67216. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  67217. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  67218. }
  67219. }
  67220. return imageData;
  67221. };
  67222. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67223. var image = pixel_data;
  67224. var width = header.width, height = header.height;
  67225. var color, i = 0, x, y;
  67226. var imageData = new Uint8Array(width * height * 4);
  67227. for (y = y_start; y !== y_end; y += y_step) {
  67228. for (x = x_start; x !== x_end; x += x_step, i++) {
  67229. color = image[i];
  67230. imageData[(x + width * y) * 4 + 0] = color;
  67231. imageData[(x + width * y) * 4 + 1] = color;
  67232. imageData[(x + width * y) * 4 + 2] = color;
  67233. imageData[(x + width * y) * 4 + 3] = 255;
  67234. }
  67235. }
  67236. return imageData;
  67237. };
  67238. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  67239. var image = pixel_data;
  67240. var width = header.width, height = header.height;
  67241. var i = 0, x, y;
  67242. var imageData = new Uint8Array(width * height * 4);
  67243. for (y = y_start; y !== y_end; y += y_step) {
  67244. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  67245. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  67246. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  67247. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  67248. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  67249. }
  67250. }
  67251. return imageData;
  67252. };
  67253. //private static _TYPE_NO_DATA = 0;
  67254. TGATools._TYPE_INDEXED = 1;
  67255. TGATools._TYPE_RGB = 2;
  67256. TGATools._TYPE_GREY = 3;
  67257. TGATools._TYPE_RLE_INDEXED = 9;
  67258. TGATools._TYPE_RLE_RGB = 10;
  67259. TGATools._TYPE_RLE_GREY = 11;
  67260. TGATools._ORIGIN_MASK = 0x30;
  67261. TGATools._ORIGIN_SHIFT = 0x04;
  67262. TGATools._ORIGIN_BL = 0x00;
  67263. TGATools._ORIGIN_BR = 0x01;
  67264. TGATools._ORIGIN_UL = 0x02;
  67265. TGATools._ORIGIN_UR = 0x03;
  67266. return TGATools;
  67267. }());
  67268. Internals.TGATools = TGATools;
  67269. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67270. })(BABYLON || (BABYLON = {}));
  67271. //# sourceMappingURL=babylon.tga.js.map
  67272. var BABYLON;
  67273. (function (BABYLON) {
  67274. var Internals;
  67275. (function (Internals) {
  67276. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  67277. // All values and structures referenced from:
  67278. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  67279. var DDS_MAGIC = 0x20534444;
  67280. var
  67281. //DDSD_CAPS = 0x1,
  67282. //DDSD_HEIGHT = 0x2,
  67283. //DDSD_WIDTH = 0x4,
  67284. //DDSD_PITCH = 0x8,
  67285. //DDSD_PIXELFORMAT = 0x1000,
  67286. DDSD_MIPMAPCOUNT = 0x20000;
  67287. //DDSD_LINEARSIZE = 0x80000,
  67288. //DDSD_DEPTH = 0x800000;
  67289. // var DDSCAPS_COMPLEX = 0x8,
  67290. // DDSCAPS_MIPMAP = 0x400000,
  67291. // DDSCAPS_TEXTURE = 0x1000;
  67292. var DDSCAPS2_CUBEMAP = 0x200;
  67293. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  67294. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  67295. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  67296. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  67297. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  67298. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  67299. // DDSCAPS2_VOLUME = 0x200000;
  67300. var
  67301. //DDPF_ALPHAPIXELS = 0x1,
  67302. //DDPF_ALPHA = 0x2,
  67303. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  67304. //DDPF_YUV = 0x200,
  67305. DDPF_LUMINANCE = 0x20000;
  67306. function FourCCToInt32(value) {
  67307. return value.charCodeAt(0) +
  67308. (value.charCodeAt(1) << 8) +
  67309. (value.charCodeAt(2) << 16) +
  67310. (value.charCodeAt(3) << 24);
  67311. }
  67312. function Int32ToFourCC(value) {
  67313. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  67314. }
  67315. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  67316. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  67317. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  67318. var FOURCC_DX10 = FourCCToInt32("DX10");
  67319. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  67320. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  67321. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  67322. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  67323. var headerLengthInt = 31; // The header length in 32 bit ints
  67324. // Offsets into the header array
  67325. var off_magic = 0;
  67326. var off_size = 1;
  67327. var off_flags = 2;
  67328. var off_height = 3;
  67329. var off_width = 4;
  67330. var off_mipmapCount = 7;
  67331. var off_pfFlags = 20;
  67332. var off_pfFourCC = 21;
  67333. var off_RGBbpp = 22;
  67334. // var off_RMask = 23;
  67335. // var off_GMask = 24;
  67336. // var off_BMask = 25;
  67337. // var off_AMask = 26;
  67338. // var off_caps1 = 27;
  67339. var off_caps2 = 28;
  67340. // var off_caps3 = 29;
  67341. // var off_caps4 = 30;
  67342. var off_dxgiFormat = 32;
  67343. ;
  67344. var DDSTools = /** @class */ (function () {
  67345. function DDSTools() {
  67346. }
  67347. DDSTools.GetDDSInfo = function (arrayBuffer) {
  67348. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  67349. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  67350. var mipmapCount = 1;
  67351. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  67352. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67353. }
  67354. var fourCC = header[off_pfFourCC];
  67355. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  67356. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67357. switch (fourCC) {
  67358. case FOURCC_D3DFMT_R16G16B16A16F:
  67359. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67360. break;
  67361. case FOURCC_D3DFMT_R32G32B32A32F:
  67362. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67363. break;
  67364. case FOURCC_DX10:
  67365. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  67366. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67367. break;
  67368. }
  67369. }
  67370. return {
  67371. width: header[off_width],
  67372. height: header[off_height],
  67373. mipmapCount: mipmapCount,
  67374. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  67375. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  67376. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  67377. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  67378. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  67379. dxgiFormat: dxgiFormat,
  67380. textureType: textureType
  67381. };
  67382. };
  67383. DDSTools._ToHalfFloat = function (value) {
  67384. if (!DDSTools._FloatView) {
  67385. DDSTools._FloatView = new Float32Array(1);
  67386. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  67387. }
  67388. DDSTools._FloatView[0] = value;
  67389. var x = DDSTools._Int32View[0];
  67390. var bits = (x >> 16) & 0x8000; /* Get the sign */
  67391. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  67392. var e = (x >> 23) & 0xff; /* Using int is faster here */
  67393. /* If zero, or denormal, or exponent underflows too much for a denormal
  67394. * half, return signed zero. */
  67395. if (e < 103) {
  67396. return bits;
  67397. }
  67398. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  67399. if (e > 142) {
  67400. bits |= 0x7c00;
  67401. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  67402. * not Inf, so make sure we set one mantissa bit too. */
  67403. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  67404. return bits;
  67405. }
  67406. /* If exponent underflows but not too much, return a denormal */
  67407. if (e < 113) {
  67408. m |= 0x0800;
  67409. /* Extra rounding may overflow and set mantissa to 0 and exponent
  67410. * to 1, which is OK. */
  67411. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  67412. return bits;
  67413. }
  67414. bits |= ((e - 112) << 10) | (m >> 1);
  67415. bits += m & 1;
  67416. return bits;
  67417. };
  67418. DDSTools._FromHalfFloat = function (value) {
  67419. var s = (value & 0x8000) >> 15;
  67420. var e = (value & 0x7C00) >> 10;
  67421. var f = value & 0x03FF;
  67422. if (e === 0) {
  67423. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  67424. }
  67425. else if (e == 0x1F) {
  67426. return f ? NaN : ((s ? -1 : 1) * Infinity);
  67427. }
  67428. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  67429. };
  67430. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67431. var destArray = new Float32Array(dataLength);
  67432. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67433. var index = 0;
  67434. for (var y = 0; y < height; y++) {
  67435. for (var x = 0; x < width; x++) {
  67436. var srcPos = (x + y * width) * 4;
  67437. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  67438. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  67439. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  67440. if (DDSTools.StoreLODInAlphaChannel) {
  67441. destArray[index + 3] = lod;
  67442. }
  67443. else {
  67444. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  67445. }
  67446. index += 4;
  67447. }
  67448. }
  67449. return destArray;
  67450. };
  67451. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67452. if (DDSTools.StoreLODInAlphaChannel) {
  67453. var destArray = new Uint16Array(dataLength);
  67454. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67455. var index = 0;
  67456. for (var y = 0; y < height; y++) {
  67457. for (var x = 0; x < width; x++) {
  67458. var srcPos = (x + y * width) * 4;
  67459. destArray[index] = srcData[srcPos];
  67460. destArray[index + 1] = srcData[srcPos + 1];
  67461. destArray[index + 2] = srcData[srcPos + 2];
  67462. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  67463. index += 4;
  67464. }
  67465. }
  67466. return destArray;
  67467. }
  67468. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  67469. };
  67470. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67471. if (DDSTools.StoreLODInAlphaChannel) {
  67472. var destArray = new Float32Array(dataLength);
  67473. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67474. var index = 0;
  67475. for (var y = 0; y < height; y++) {
  67476. for (var x = 0; x < width; x++) {
  67477. var srcPos = (x + y * width) * 4;
  67478. destArray[index] = srcData[srcPos];
  67479. destArray[index + 1] = srcData[srcPos + 1];
  67480. destArray[index + 2] = srcData[srcPos + 2];
  67481. destArray[index + 3] = lod;
  67482. index += 4;
  67483. }
  67484. }
  67485. return destArray;
  67486. }
  67487. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  67488. };
  67489. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67490. var destArray = new Uint8Array(dataLength);
  67491. var srcData = new Float32Array(arrayBuffer, dataOffset);
  67492. var index = 0;
  67493. for (var y = 0; y < height; y++) {
  67494. for (var x = 0; x < width; x++) {
  67495. var srcPos = (x + y * width) * 4;
  67496. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  67497. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  67498. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  67499. if (DDSTools.StoreLODInAlphaChannel) {
  67500. destArray[index + 3] = lod;
  67501. }
  67502. else {
  67503. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  67504. }
  67505. index += 4;
  67506. }
  67507. }
  67508. return destArray;
  67509. };
  67510. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  67511. var destArray = new Uint8Array(dataLength);
  67512. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  67513. var index = 0;
  67514. for (var y = 0; y < height; y++) {
  67515. for (var x = 0; x < width; x++) {
  67516. var srcPos = (x + y * width) * 4;
  67517. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  67518. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  67519. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  67520. if (DDSTools.StoreLODInAlphaChannel) {
  67521. destArray[index + 3] = lod;
  67522. }
  67523. else {
  67524. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  67525. }
  67526. index += 4;
  67527. }
  67528. }
  67529. return destArray;
  67530. };
  67531. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67532. var byteArray = new Uint8Array(dataLength);
  67533. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67534. var index = 0;
  67535. for (var y = 0; y < height; y++) {
  67536. for (var x = 0; x < width; x++) {
  67537. var srcPos = (x + y * width) * 4;
  67538. byteArray[index] = srcData[srcPos + 2];
  67539. byteArray[index + 1] = srcData[srcPos + 1];
  67540. byteArray[index + 2] = srcData[srcPos];
  67541. byteArray[index + 3] = srcData[srcPos + 3];
  67542. index += 4;
  67543. }
  67544. }
  67545. return byteArray;
  67546. };
  67547. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67548. var byteArray = new Uint8Array(dataLength);
  67549. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67550. var index = 0;
  67551. for (var y = 0; y < height; y++) {
  67552. for (var x = 0; x < width; x++) {
  67553. var srcPos = (x + y * width) * 3;
  67554. byteArray[index] = srcData[srcPos + 2];
  67555. byteArray[index + 1] = srcData[srcPos + 1];
  67556. byteArray[index + 2] = srcData[srcPos];
  67557. index += 3;
  67558. }
  67559. }
  67560. return byteArray;
  67561. };
  67562. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  67563. var byteArray = new Uint8Array(dataLength);
  67564. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  67565. var index = 0;
  67566. for (var y = 0; y < height; y++) {
  67567. for (var x = 0; x < width; x++) {
  67568. var srcPos = (x + y * width);
  67569. byteArray[index] = srcData[srcPos];
  67570. index++;
  67571. }
  67572. }
  67573. return byteArray;
  67574. };
  67575. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  67576. if (lodIndex === void 0) { lodIndex = -1; }
  67577. var ext = engine.getCaps().s3tc;
  67578. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  67579. var internalFormat = 0;
  67580. var format = 0;
  67581. var blockBytes = 1;
  67582. if (header[off_magic] != DDS_MAGIC) {
  67583. BABYLON.Tools.Error("Invalid magic number in DDS header");
  67584. return;
  67585. }
  67586. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  67587. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  67588. return;
  67589. }
  67590. if (info.isCompressed && !ext) {
  67591. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  67592. return;
  67593. }
  67594. var bpp = header[off_RGBbpp];
  67595. dataOffset = header[off_size] + 4;
  67596. var computeFormats = false;
  67597. if (info.isFourCC) {
  67598. fourCC = header[off_pfFourCC];
  67599. switch (fourCC) {
  67600. case FOURCC_DXT1:
  67601. blockBytes = 8;
  67602. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  67603. break;
  67604. case FOURCC_DXT3:
  67605. blockBytes = 16;
  67606. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  67607. break;
  67608. case FOURCC_DXT5:
  67609. blockBytes = 16;
  67610. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  67611. break;
  67612. case FOURCC_D3DFMT_R16G16B16A16F:
  67613. computeFormats = true;
  67614. break;
  67615. case FOURCC_D3DFMT_R32G32B32A32F:
  67616. computeFormats = true;
  67617. break;
  67618. case FOURCC_DX10:
  67619. // There is an additionnal header so dataOffset need to be changed
  67620. dataOffset += 5 * 4; // 5 uints
  67621. var supported = false;
  67622. switch (info.dxgiFormat) {
  67623. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  67624. computeFormats = true;
  67625. supported = true;
  67626. break;
  67627. case DXGI_FORMAT_B8G8R8X8_UNORM:
  67628. info.isRGB = true;
  67629. info.isFourCC = false;
  67630. bpp = 32;
  67631. supported = true;
  67632. break;
  67633. }
  67634. if (supported) {
  67635. break;
  67636. }
  67637. default:
  67638. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  67639. return;
  67640. }
  67641. }
  67642. if (computeFormats) {
  67643. format = engine._getWebGLTextureType(info.textureType);
  67644. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67645. }
  67646. mipmapCount = 1;
  67647. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  67648. mipmapCount = Math.max(1, header[off_mipmapCount]);
  67649. }
  67650. for (var face = 0; face < faces; face++) {
  67651. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67652. width = header[off_width];
  67653. height = header[off_height];
  67654. for (mip = 0; mip < mipmapCount; ++mip) {
  67655. if (lodIndex === -1 || lodIndex === mip) {
  67656. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  67657. var i = (lodIndex === -1) ? mip : 0;
  67658. if (!info.isCompressed && info.isFourCC) {
  67659. dataLength = width * height * 4;
  67660. var FloatArray = null;
  67661. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  67662. if (bpp === 128) {
  67663. FloatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67664. }
  67665. else if (bpp === 64) {
  67666. FloatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67667. }
  67668. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67669. format = engine._getWebGLTextureType(info.textureType);
  67670. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67671. }
  67672. else {
  67673. if (bpp === 128) {
  67674. FloatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67675. }
  67676. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  67677. FloatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67678. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67679. format = engine._getWebGLTextureType(info.textureType);
  67680. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  67681. }
  67682. else {
  67683. FloatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  67684. }
  67685. }
  67686. if (FloatArray) {
  67687. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, FloatArray);
  67688. }
  67689. }
  67690. else if (info.isRGB) {
  67691. if (bpp === 24) {
  67692. dataLength = width * height * 3;
  67693. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67694. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  67695. }
  67696. else {
  67697. dataLength = width * height * 4;
  67698. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67699. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  67700. }
  67701. }
  67702. else if (info.isLuminance) {
  67703. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  67704. var unpaddedRowSize = width;
  67705. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  67706. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  67707. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  67708. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  67709. }
  67710. else {
  67711. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  67712. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  67713. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  67714. }
  67715. }
  67716. dataOffset += width * height * (bpp / 8);
  67717. width *= 0.5;
  67718. height *= 0.5;
  67719. width = Math.max(1.0, width);
  67720. height = Math.max(1.0, height);
  67721. }
  67722. }
  67723. };
  67724. DDSTools.StoreLODInAlphaChannel = false;
  67725. return DDSTools;
  67726. }());
  67727. Internals.DDSTools = DDSTools;
  67728. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67729. })(BABYLON || (BABYLON = {}));
  67730. //# sourceMappingURL=babylon.dds.js.map
  67731. var BABYLON;
  67732. (function (BABYLON) {
  67733. var Internals;
  67734. (function (Internals) {
  67735. /**
  67736. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  67737. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  67738. */
  67739. var KhronosTextureContainer = /** @class */ (function () {
  67740. /**
  67741. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  67742. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  67743. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  67744. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  67745. */
  67746. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  67747. this.arrayBuffer = arrayBuffer;
  67748. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  67749. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  67750. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  67751. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  67752. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  67753. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  67754. BABYLON.Tools.Error("texture missing KTX identifier");
  67755. return;
  67756. }
  67757. // load the reset of the header in native 32 bit int
  67758. var header = new Int32Array(this.arrayBuffer, 12, 13);
  67759. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  67760. var oppositeEndianess = header[0] === 0x01020304;
  67761. // read all the header elements in order they exist in the file, without modification (sans endainness)
  67762. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  67763. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  67764. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  67765. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  67766. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  67767. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  67768. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  67769. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  67770. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  67771. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  67772. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  67773. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  67774. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  67775. if (this.glType !== 0) {
  67776. BABYLON.Tools.Error("only compressed formats currently supported");
  67777. return;
  67778. }
  67779. else {
  67780. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  67781. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  67782. }
  67783. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  67784. BABYLON.Tools.Error("only 2D textures currently supported");
  67785. return;
  67786. }
  67787. if (this.numberOfArrayElements !== 0) {
  67788. BABYLON.Tools.Error("texture arrays not currently supported");
  67789. return;
  67790. }
  67791. if (this.numberOfFaces !== facesExpected) {
  67792. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  67793. return;
  67794. }
  67795. // we now have a completely validated file, so could use existence of loadType as success
  67796. // would need to make this more elaborate & adjust checks above to support more than one load type
  67797. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  67798. }
  67799. // not as fast hardware based, but will probably never need to use
  67800. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  67801. return ((val & 0xFF) << 24)
  67802. | ((val & 0xFF00) << 8)
  67803. | ((val >> 8) & 0xFF00)
  67804. | ((val >> 24) & 0xFF);
  67805. };
  67806. /**
  67807. * It is assumed that the texture has already been created & is currently bound
  67808. */
  67809. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  67810. switch (this.loadType) {
  67811. case KhronosTextureContainer.COMPRESSED_2D:
  67812. this._upload2DCompressedLevels(gl, loadMipmaps);
  67813. break;
  67814. case KhronosTextureContainer.TEX_2D:
  67815. case KhronosTextureContainer.COMPRESSED_3D:
  67816. case KhronosTextureContainer.TEX_3D:
  67817. }
  67818. };
  67819. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  67820. // initialize width & height for level 1
  67821. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  67822. var width = this.pixelWidth;
  67823. var height = this.pixelHeight;
  67824. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  67825. for (var level = 0; level < mipmapCount; level++) {
  67826. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  67827. for (var face = 0; face < this.numberOfFaces; face++) {
  67828. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  67829. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  67830. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  67831. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  67832. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  67833. }
  67834. width = Math.max(1.0, width * 0.5);
  67835. height = Math.max(1.0, height * 0.5);
  67836. }
  67837. };
  67838. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  67839. // load types
  67840. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  67841. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  67842. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  67843. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  67844. return KhronosTextureContainer;
  67845. }());
  67846. Internals.KhronosTextureContainer = KhronosTextureContainer;
  67847. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  67848. })(BABYLON || (BABYLON = {}));
  67849. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  67850. var BABYLON;
  67851. (function (BABYLON) {
  67852. var Debug;
  67853. (function (Debug) {
  67854. /**
  67855. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  67856. */
  67857. var SkeletonViewer = /** @class */ (function () {
  67858. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  67859. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  67860. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  67861. this.skeleton = skeleton;
  67862. this.mesh = mesh;
  67863. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  67864. this.renderingGroupId = renderingGroupId;
  67865. this.color = BABYLON.Color3.White();
  67866. this._debugLines = new Array();
  67867. this._isEnabled = false;
  67868. this._scene = scene;
  67869. this.update();
  67870. this._renderFunction = this.update.bind(this);
  67871. }
  67872. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  67873. get: function () {
  67874. return this._isEnabled;
  67875. },
  67876. set: function (value) {
  67877. if (this._isEnabled === value) {
  67878. return;
  67879. }
  67880. this._isEnabled = value;
  67881. if (value) {
  67882. this._scene.registerBeforeRender(this._renderFunction);
  67883. }
  67884. else {
  67885. this._scene.unregisterBeforeRender(this._renderFunction);
  67886. }
  67887. },
  67888. enumerable: true,
  67889. configurable: true
  67890. });
  67891. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  67892. if (x === void 0) { x = 0; }
  67893. if (y === void 0) { y = 0; }
  67894. if (z === void 0) { z = 0; }
  67895. var tmat = BABYLON.Tmp.Matrix[0];
  67896. var parentBone = bone.getParent();
  67897. tmat.copyFrom(bone.getLocalMatrix());
  67898. if (x !== 0 || y !== 0 || z !== 0) {
  67899. var tmat2 = BABYLON.Tmp.Matrix[1];
  67900. BABYLON.Matrix.IdentityToRef(tmat2);
  67901. tmat2.m[12] = x;
  67902. tmat2.m[13] = y;
  67903. tmat2.m[14] = z;
  67904. tmat2.multiplyToRef(tmat, tmat);
  67905. }
  67906. if (parentBone) {
  67907. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  67908. }
  67909. tmat.multiplyToRef(meshMat, tmat);
  67910. position.x = tmat.m[12];
  67911. position.y = tmat.m[13];
  67912. position.z = tmat.m[14];
  67913. };
  67914. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  67915. var len = bones.length;
  67916. var meshPos = this.mesh.position;
  67917. for (var i = 0; i < len; i++) {
  67918. var bone = bones[i];
  67919. var points = this._debugLines[i];
  67920. if (!points) {
  67921. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67922. this._debugLines[i] = points;
  67923. }
  67924. this._getBonePosition(points[0], bone, meshMat);
  67925. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  67926. points[0].subtractInPlace(meshPos);
  67927. points[1].subtractInPlace(meshPos);
  67928. }
  67929. };
  67930. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  67931. var len = bones.length;
  67932. var boneNum = 0;
  67933. var meshPos = this.mesh.position;
  67934. for (var i = len - 1; i >= 0; i--) {
  67935. var childBone = bones[i];
  67936. var parentBone = childBone.getParent();
  67937. if (!parentBone) {
  67938. continue;
  67939. }
  67940. var points = this._debugLines[boneNum];
  67941. if (!points) {
  67942. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67943. this._debugLines[boneNum] = points;
  67944. }
  67945. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  67946. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  67947. points[0].subtractInPlace(meshPos);
  67948. points[1].subtractInPlace(meshPos);
  67949. boneNum++;
  67950. }
  67951. };
  67952. SkeletonViewer.prototype.update = function () {
  67953. if (this.autoUpdateBonesMatrices) {
  67954. this.skeleton.computeAbsoluteTransforms();
  67955. }
  67956. if (this.skeleton.bones[0].length === undefined) {
  67957. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67958. }
  67959. else {
  67960. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  67961. }
  67962. if (!this._debugMesh) {
  67963. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  67964. this._debugMesh.renderingGroupId = this.renderingGroupId;
  67965. }
  67966. else {
  67967. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  67968. }
  67969. this._debugMesh.position.copyFrom(this.mesh.position);
  67970. this._debugMesh.color = this.color;
  67971. };
  67972. SkeletonViewer.prototype.dispose = function () {
  67973. if (this._debugMesh) {
  67974. this.isEnabled = false;
  67975. this._debugMesh.dispose();
  67976. this._debugMesh = null;
  67977. }
  67978. };
  67979. return SkeletonViewer;
  67980. }());
  67981. Debug.SkeletonViewer = SkeletonViewer;
  67982. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  67983. })(BABYLON || (BABYLON = {}));
  67984. //# sourceMappingURL=babylon.skeletonViewer.js.map
  67985. var BABYLON;
  67986. (function (BABYLON) {
  67987. var Debug;
  67988. (function (Debug) {
  67989. var AxesViewer = /** @class */ (function () {
  67990. function AxesViewer(scene, scaleLines) {
  67991. if (scaleLines === void 0) { scaleLines = 1; }
  67992. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67993. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67994. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67995. this.scaleLines = 1;
  67996. this.scaleLines = scaleLines;
  67997. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  67998. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  67999. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  68000. this._xmesh.renderingGroupId = 2;
  68001. this._ymesh.renderingGroupId = 2;
  68002. this._zmesh.renderingGroupId = 2;
  68003. this._xmesh.material.checkReadyOnlyOnce = true;
  68004. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  68005. this._ymesh.material.checkReadyOnlyOnce = true;
  68006. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  68007. this._zmesh.material.checkReadyOnlyOnce = true;
  68008. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  68009. this.scene = scene;
  68010. }
  68011. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  68012. var scaleLines = this.scaleLines;
  68013. if (this._xmesh) {
  68014. this._xmesh.position.copyFrom(position);
  68015. }
  68016. if (this._ymesh) {
  68017. this._ymesh.position.copyFrom(position);
  68018. }
  68019. if (this._zmesh) {
  68020. this._zmesh.position.copyFrom(position);
  68021. }
  68022. var point2 = this._xline[1];
  68023. point2.x = xaxis.x * scaleLines;
  68024. point2.y = xaxis.y * scaleLines;
  68025. point2.z = xaxis.z * scaleLines;
  68026. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  68027. point2 = this._yline[1];
  68028. point2.x = yaxis.x * scaleLines;
  68029. point2.y = yaxis.y * scaleLines;
  68030. point2.z = yaxis.z * scaleLines;
  68031. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  68032. point2 = this._zline[1];
  68033. point2.x = zaxis.x * scaleLines;
  68034. point2.y = zaxis.y * scaleLines;
  68035. point2.z = zaxis.z * scaleLines;
  68036. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  68037. };
  68038. AxesViewer.prototype.dispose = function () {
  68039. if (this._xmesh) {
  68040. this._xmesh.dispose();
  68041. }
  68042. if (this._ymesh) {
  68043. this._ymesh.dispose();
  68044. }
  68045. if (this._zmesh) {
  68046. this._zmesh.dispose();
  68047. }
  68048. this._xmesh = null;
  68049. this._ymesh = null;
  68050. this._zmesh = null;
  68051. this.scene = null;
  68052. };
  68053. return AxesViewer;
  68054. }());
  68055. Debug.AxesViewer = AxesViewer;
  68056. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68057. })(BABYLON || (BABYLON = {}));
  68058. //# sourceMappingURL=babylon.axesViewer.js.map
  68059. var BABYLON;
  68060. (function (BABYLON) {
  68061. var Debug;
  68062. (function (Debug) {
  68063. var BoneAxesViewer = /** @class */ (function (_super) {
  68064. __extends(BoneAxesViewer, _super);
  68065. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  68066. if (scaleLines === void 0) { scaleLines = 1; }
  68067. var _this = _super.call(this, scene, scaleLines) || this;
  68068. _this.pos = BABYLON.Vector3.Zero();
  68069. _this.xaxis = BABYLON.Vector3.Zero();
  68070. _this.yaxis = BABYLON.Vector3.Zero();
  68071. _this.zaxis = BABYLON.Vector3.Zero();
  68072. _this.mesh = mesh;
  68073. _this.bone = bone;
  68074. return _this;
  68075. }
  68076. BoneAxesViewer.prototype.update = function () {
  68077. if (!this.mesh || !this.bone) {
  68078. return;
  68079. }
  68080. var bone = this.bone;
  68081. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  68082. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  68083. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  68084. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  68085. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  68086. };
  68087. BoneAxesViewer.prototype.dispose = function () {
  68088. if (this.mesh) {
  68089. this.mesh = null;
  68090. this.bone = null;
  68091. _super.prototype.dispose.call(this);
  68092. }
  68093. };
  68094. return BoneAxesViewer;
  68095. }(Debug.AxesViewer));
  68096. Debug.BoneAxesViewer = BoneAxesViewer;
  68097. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68098. })(BABYLON || (BABYLON = {}));
  68099. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  68100. var BABYLON;
  68101. (function (BABYLON) {
  68102. var RayHelper = /** @class */ (function () {
  68103. function RayHelper(ray) {
  68104. this.ray = ray;
  68105. }
  68106. RayHelper.CreateAndShow = function (ray, scene, color) {
  68107. var helper = new RayHelper(ray);
  68108. helper.show(scene, color);
  68109. return helper;
  68110. };
  68111. RayHelper.prototype.show = function (scene, color) {
  68112. if (!this._renderFunction && this.ray) {
  68113. var ray = this.ray;
  68114. this._renderFunction = this._render.bind(this);
  68115. this._scene = scene;
  68116. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  68117. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  68118. if (this._renderFunction) {
  68119. this._scene.registerBeforeRender(this._renderFunction);
  68120. }
  68121. }
  68122. if (color && this._renderLine) {
  68123. this._renderLine.color.copyFrom(color);
  68124. }
  68125. };
  68126. RayHelper.prototype.hide = function () {
  68127. if (this._renderFunction && this._scene) {
  68128. this._scene.unregisterBeforeRender(this._renderFunction);
  68129. this._scene = null;
  68130. this._renderFunction = null;
  68131. if (this._renderLine) {
  68132. this._renderLine.dispose();
  68133. this._renderLine = null;
  68134. }
  68135. this._renderPoints = [];
  68136. }
  68137. };
  68138. RayHelper.prototype._render = function () {
  68139. var ray = this.ray;
  68140. if (!ray) {
  68141. return;
  68142. }
  68143. var point = this._renderPoints[1];
  68144. var len = Math.min(ray.length, 1000000);
  68145. point.copyFrom(ray.direction);
  68146. point.scaleInPlace(len);
  68147. point.addInPlace(ray.origin);
  68148. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  68149. };
  68150. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  68151. this._attachedToMesh = mesh;
  68152. var ray = this.ray;
  68153. if (!ray) {
  68154. return;
  68155. }
  68156. if (!ray.direction) {
  68157. ray.direction = BABYLON.Vector3.Zero();
  68158. }
  68159. if (!ray.origin) {
  68160. ray.origin = BABYLON.Vector3.Zero();
  68161. }
  68162. if (length) {
  68163. ray.length = length;
  68164. }
  68165. if (!meshSpaceOrigin) {
  68166. meshSpaceOrigin = BABYLON.Vector3.Zero();
  68167. }
  68168. if (!meshSpaceDirection) {
  68169. // -1 so that this will work with Mesh.lookAt
  68170. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  68171. }
  68172. if (!this._meshSpaceDirection) {
  68173. this._meshSpaceDirection = meshSpaceDirection.clone();
  68174. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  68175. }
  68176. else {
  68177. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  68178. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  68179. }
  68180. if (!this._updateToMeshFunction) {
  68181. this._updateToMeshFunction = this._updateToMesh.bind(this);
  68182. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  68183. }
  68184. this._updateToMesh();
  68185. };
  68186. RayHelper.prototype.detachFromMesh = function () {
  68187. if (this._attachedToMesh) {
  68188. if (this._updateToMeshFunction) {
  68189. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  68190. }
  68191. this._attachedToMesh = null;
  68192. this._updateToMeshFunction = null;
  68193. }
  68194. };
  68195. RayHelper.prototype._updateToMesh = function () {
  68196. var ray = this.ray;
  68197. if (!this._attachedToMesh || !ray) {
  68198. return;
  68199. }
  68200. if (this._attachedToMesh._isDisposed) {
  68201. this.detachFromMesh();
  68202. return;
  68203. }
  68204. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  68205. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  68206. };
  68207. RayHelper.prototype.dispose = function () {
  68208. this.hide();
  68209. this.detachFromMesh();
  68210. this.ray = null;
  68211. };
  68212. return RayHelper;
  68213. }());
  68214. BABYLON.RayHelper = RayHelper;
  68215. })(BABYLON || (BABYLON = {}));
  68216. //# sourceMappingURL=babylon.rayHelper.js.map
  68217. var BABYLON;
  68218. (function (BABYLON) {
  68219. var DebugLayer = /** @class */ (function () {
  68220. function DebugLayer(scene) {
  68221. this._scene = scene;
  68222. }
  68223. /** Creates the inspector window. */
  68224. DebugLayer.prototype._createInspector = function (config) {
  68225. if (config === void 0) { config = {}; }
  68226. var popup = config.popup || false;
  68227. var initialTab = config.initialTab || 0;
  68228. var parentElement = config.parentElement || null;
  68229. if (!this._inspector) {
  68230. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  68231. } // else nothing to do,; instance is already existing
  68232. };
  68233. DebugLayer.prototype.isVisible = function () {
  68234. if (!this._inspector) {
  68235. return false;
  68236. }
  68237. return true;
  68238. };
  68239. DebugLayer.prototype.hide = function () {
  68240. if (this._inspector) {
  68241. try {
  68242. this._inspector.dispose();
  68243. }
  68244. catch (e) {
  68245. // If the inspector has been removed directly from the inspector tool
  68246. }
  68247. this._inspector = null;
  68248. }
  68249. };
  68250. DebugLayer.prototype.show = function (config) {
  68251. if (config === void 0) { config = {}; }
  68252. if (typeof INSPECTOR == 'undefined') {
  68253. // Load inspector and add it to the DOM
  68254. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  68255. }
  68256. else {
  68257. // Otherwise creates the inspector
  68258. this._createInspector(config);
  68259. }
  68260. };
  68261. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  68262. return DebugLayer;
  68263. }());
  68264. BABYLON.DebugLayer = DebugLayer;
  68265. })(BABYLON || (BABYLON = {}));
  68266. //# sourceMappingURL=babylon.debugLayer.js.map
  68267. var BABYLON;
  68268. (function (BABYLON) {
  68269. var Debug;
  68270. (function (Debug) {
  68271. var PhysicsViewer = /** @class */ (function () {
  68272. function PhysicsViewer(scene) {
  68273. this._impostors = [];
  68274. this._meshes = [];
  68275. this._numMeshes = 0;
  68276. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  68277. var physicEngine = this._scene.getPhysicsEngine();
  68278. if (physicEngine) {
  68279. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  68280. }
  68281. }
  68282. PhysicsViewer.prototype._updateDebugMeshes = function () {
  68283. var plugin = this._physicsEnginePlugin;
  68284. for (var i = 0; i < this._numMeshes; i++) {
  68285. var impostor = this._impostors[i];
  68286. if (!impostor) {
  68287. continue;
  68288. }
  68289. if (impostor.isDisposed) {
  68290. this.hideImpostor(this._impostors[i--]);
  68291. }
  68292. else {
  68293. var mesh = this._meshes[i];
  68294. if (mesh && plugin) {
  68295. plugin.syncMeshWithImpostor(mesh, impostor);
  68296. }
  68297. }
  68298. }
  68299. };
  68300. PhysicsViewer.prototype.showImpostor = function (impostor) {
  68301. if (!this._scene) {
  68302. return;
  68303. }
  68304. for (var i = 0; i < this._numMeshes; i++) {
  68305. if (this._impostors[i] == impostor) {
  68306. return;
  68307. }
  68308. }
  68309. var debugMesh = this._getDebugMesh(impostor, this._scene);
  68310. if (debugMesh) {
  68311. this._impostors[this._numMeshes] = impostor;
  68312. this._meshes[this._numMeshes] = debugMesh;
  68313. if (this._numMeshes === 0) {
  68314. this._renderFunction = this._updateDebugMeshes.bind(this);
  68315. this._scene.registerBeforeRender(this._renderFunction);
  68316. }
  68317. this._numMeshes++;
  68318. }
  68319. };
  68320. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  68321. if (!impostor || !this._scene) {
  68322. return;
  68323. }
  68324. var removed = false;
  68325. for (var i = 0; i < this._numMeshes; i++) {
  68326. if (this._impostors[i] == impostor) {
  68327. var mesh = this._meshes[i];
  68328. if (!mesh) {
  68329. continue;
  68330. }
  68331. this._scene.removeMesh(mesh);
  68332. mesh.dispose();
  68333. this._numMeshes--;
  68334. if (this._numMeshes > 0) {
  68335. this._meshes[i] = this._meshes[this._numMeshes];
  68336. this._impostors[i] = this._impostors[this._numMeshes];
  68337. this._meshes[this._numMeshes] = null;
  68338. this._impostors[this._numMeshes] = null;
  68339. }
  68340. else {
  68341. this._meshes[0] = null;
  68342. this._impostors[0] = null;
  68343. }
  68344. removed = true;
  68345. break;
  68346. }
  68347. }
  68348. if (removed && this._numMeshes === 0) {
  68349. this._scene.unregisterBeforeRender(this._renderFunction);
  68350. }
  68351. };
  68352. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  68353. if (!this._debugMaterial) {
  68354. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  68355. this._debugMaterial.wireframe = true;
  68356. }
  68357. return this._debugMaterial;
  68358. };
  68359. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  68360. if (!this._debugBoxMesh) {
  68361. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  68362. this._debugBoxMesh.renderingGroupId = 1;
  68363. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68364. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  68365. scene.removeMesh(this._debugBoxMesh);
  68366. }
  68367. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  68368. };
  68369. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  68370. if (!this._debugSphereMesh) {
  68371. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  68372. this._debugSphereMesh.renderingGroupId = 1;
  68373. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  68374. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  68375. scene.removeMesh(this._debugSphereMesh);
  68376. }
  68377. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  68378. };
  68379. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  68380. var mesh = null;
  68381. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  68382. mesh = this._getDebugBoxMesh(scene);
  68383. impostor.getBoxSizeToRef(mesh.scaling);
  68384. }
  68385. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  68386. mesh = this._getDebugSphereMesh(scene);
  68387. var radius = impostor.getRadius();
  68388. mesh.scaling.x = radius * 2;
  68389. mesh.scaling.y = radius * 2;
  68390. mesh.scaling.z = radius * 2;
  68391. }
  68392. return mesh;
  68393. };
  68394. PhysicsViewer.prototype.dispose = function () {
  68395. for (var i = 0; i < this._numMeshes; i++) {
  68396. this.hideImpostor(this._impostors[i]);
  68397. }
  68398. if (this._debugBoxMesh) {
  68399. this._debugBoxMesh.dispose();
  68400. }
  68401. if (this._debugSphereMesh) {
  68402. this._debugSphereMesh.dispose();
  68403. }
  68404. if (this._debugMaterial) {
  68405. this._debugMaterial.dispose();
  68406. }
  68407. this._impostors.length = 0;
  68408. this._scene = null;
  68409. this._physicsEnginePlugin = null;
  68410. };
  68411. return PhysicsViewer;
  68412. }());
  68413. Debug.PhysicsViewer = PhysicsViewer;
  68414. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  68415. })(BABYLON || (BABYLON = {}));
  68416. //# sourceMappingURL=babylon.physicsViewer.js.map
  68417. var BABYLON;
  68418. (function (BABYLON) {
  68419. var BoundingBoxRenderer = /** @class */ (function () {
  68420. function BoundingBoxRenderer(scene) {
  68421. this.frontColor = new BABYLON.Color3(1, 1, 1);
  68422. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  68423. this.showBackLines = true;
  68424. this.renderList = new BABYLON.SmartArray(32);
  68425. this._vertexBuffers = {};
  68426. this._scene = scene;
  68427. }
  68428. BoundingBoxRenderer.prototype._prepareRessources = function () {
  68429. if (this._colorShader) {
  68430. return;
  68431. }
  68432. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  68433. attributes: [BABYLON.VertexBuffer.PositionKind],
  68434. uniforms: ["world", "viewProjection", "color"]
  68435. });
  68436. var engine = this._scene.getEngine();
  68437. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  68438. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  68439. this._createIndexBuffer();
  68440. };
  68441. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  68442. var engine = this._scene.getEngine();
  68443. 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]);
  68444. };
  68445. BoundingBoxRenderer.prototype._rebuild = function () {
  68446. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68447. if (vb) {
  68448. vb._rebuild();
  68449. }
  68450. this._createIndexBuffer();
  68451. };
  68452. BoundingBoxRenderer.prototype.reset = function () {
  68453. this.renderList.reset();
  68454. };
  68455. BoundingBoxRenderer.prototype.render = function () {
  68456. if (this.renderList.length === 0) {
  68457. return;
  68458. }
  68459. this._prepareRessources();
  68460. if (!this._colorShader.isReady()) {
  68461. return;
  68462. }
  68463. var engine = this._scene.getEngine();
  68464. engine.setDepthWrite(false);
  68465. this._colorShader._preBind();
  68466. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  68467. var boundingBox = this.renderList.data[boundingBoxIndex];
  68468. var min = boundingBox.minimum;
  68469. var max = boundingBox.maximum;
  68470. var diff = max.subtract(min);
  68471. var median = min.add(diff.scale(0.5));
  68472. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68473. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68474. .multiply(boundingBox.getWorldMatrix());
  68475. // VBOs
  68476. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68477. if (this.showBackLines) {
  68478. // Back
  68479. engine.setDepthFunctionToGreaterOrEqual();
  68480. this._scene.resetCachedMaterial();
  68481. this._colorShader.setColor4("color", this.backColor.toColor4());
  68482. this._colorShader.bind(worldMatrix);
  68483. // Draw order
  68484. engine.draw(false, 0, 24);
  68485. }
  68486. // Front
  68487. engine.setDepthFunctionToLess();
  68488. this._scene.resetCachedMaterial();
  68489. this._colorShader.setColor4("color", this.frontColor.toColor4());
  68490. this._colorShader.bind(worldMatrix);
  68491. // Draw order
  68492. engine.draw(false, 0, 24);
  68493. }
  68494. this._colorShader.unbind();
  68495. engine.setDepthFunctionToLessOrEqual();
  68496. engine.setDepthWrite(true);
  68497. };
  68498. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  68499. this._prepareRessources();
  68500. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  68501. return;
  68502. }
  68503. var engine = this._scene.getEngine();
  68504. engine.setDepthWrite(false);
  68505. engine.setColorWrite(false);
  68506. this._colorShader._preBind();
  68507. var boundingBox = mesh._boundingInfo.boundingBox;
  68508. var min = boundingBox.minimum;
  68509. var max = boundingBox.maximum;
  68510. var diff = max.subtract(min);
  68511. var median = min.add(diff.scale(0.5));
  68512. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  68513. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  68514. .multiply(boundingBox.getWorldMatrix());
  68515. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  68516. engine.setDepthFunctionToLess();
  68517. this._scene.resetCachedMaterial();
  68518. this._colorShader.bind(worldMatrix);
  68519. engine.draw(false, 0, 24);
  68520. this._colorShader.unbind();
  68521. engine.setDepthFunctionToLessOrEqual();
  68522. engine.setDepthWrite(true);
  68523. engine.setColorWrite(true);
  68524. };
  68525. BoundingBoxRenderer.prototype.dispose = function () {
  68526. if (!this._colorShader) {
  68527. return;
  68528. }
  68529. this.renderList.dispose();
  68530. this._colorShader.dispose();
  68531. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68532. if (buffer) {
  68533. buffer.dispose();
  68534. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  68535. }
  68536. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  68537. };
  68538. return BoundingBoxRenderer;
  68539. }());
  68540. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  68541. })(BABYLON || (BABYLON = {}));
  68542. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  68543. var BABYLON;
  68544. (function (BABYLON) {
  68545. var MorphTarget = /** @class */ (function () {
  68546. function MorphTarget(name, influence) {
  68547. if (influence === void 0) { influence = 0; }
  68548. this.name = name;
  68549. this.animations = new Array();
  68550. this._positions = null;
  68551. this._normals = null;
  68552. this._tangents = null;
  68553. this.onInfluenceChanged = new BABYLON.Observable();
  68554. this.influence = influence;
  68555. }
  68556. Object.defineProperty(MorphTarget.prototype, "influence", {
  68557. get: function () {
  68558. return this._influence;
  68559. },
  68560. set: function (influence) {
  68561. if (this._influence === influence) {
  68562. return;
  68563. }
  68564. var previous = this._influence;
  68565. this._influence = influence;
  68566. if (this.onInfluenceChanged.hasObservers) {
  68567. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  68568. }
  68569. },
  68570. enumerable: true,
  68571. configurable: true
  68572. });
  68573. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  68574. get: function () {
  68575. return !!this._positions;
  68576. },
  68577. enumerable: true,
  68578. configurable: true
  68579. });
  68580. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  68581. get: function () {
  68582. return !!this._normals;
  68583. },
  68584. enumerable: true,
  68585. configurable: true
  68586. });
  68587. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  68588. get: function () {
  68589. return !!this._tangents;
  68590. },
  68591. enumerable: true,
  68592. configurable: true
  68593. });
  68594. MorphTarget.prototype.setPositions = function (data) {
  68595. this._positions = data;
  68596. };
  68597. MorphTarget.prototype.getPositions = function () {
  68598. return this._positions;
  68599. };
  68600. MorphTarget.prototype.setNormals = function (data) {
  68601. this._normals = data;
  68602. };
  68603. MorphTarget.prototype.getNormals = function () {
  68604. return this._normals;
  68605. };
  68606. MorphTarget.prototype.setTangents = function (data) {
  68607. this._tangents = data;
  68608. };
  68609. MorphTarget.prototype.getTangents = function () {
  68610. return this._tangents;
  68611. };
  68612. /**
  68613. * Serializes the current target into a Serialization object.
  68614. * Returns the serialized object.
  68615. */
  68616. MorphTarget.prototype.serialize = function () {
  68617. var serializationObject = {};
  68618. serializationObject.name = this.name;
  68619. serializationObject.influence = this.influence;
  68620. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  68621. if (this.hasNormals) {
  68622. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  68623. }
  68624. if (this.hasTangents) {
  68625. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  68626. }
  68627. // Animations
  68628. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  68629. return serializationObject;
  68630. };
  68631. // Statics
  68632. MorphTarget.Parse = function (serializationObject) {
  68633. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  68634. result.setPositions(serializationObject.positions);
  68635. if (serializationObject.normals) {
  68636. result.setNormals(serializationObject.normals);
  68637. }
  68638. if (serializationObject.tangents) {
  68639. result.setTangents(serializationObject.tangents);
  68640. }
  68641. // Animations
  68642. if (serializationObject.animations) {
  68643. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  68644. var parsedAnimation = serializationObject.animations[animationIndex];
  68645. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  68646. }
  68647. }
  68648. return result;
  68649. };
  68650. MorphTarget.FromMesh = function (mesh, name, influence) {
  68651. if (!name) {
  68652. name = mesh.name;
  68653. }
  68654. var result = new MorphTarget(name, influence);
  68655. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68656. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  68657. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  68658. }
  68659. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  68660. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  68661. }
  68662. return result;
  68663. };
  68664. return MorphTarget;
  68665. }());
  68666. BABYLON.MorphTarget = MorphTarget;
  68667. })(BABYLON || (BABYLON = {}));
  68668. //# sourceMappingURL=babylon.morphTarget.js.map
  68669. var BABYLON;
  68670. (function (BABYLON) {
  68671. var MorphTargetManager = /** @class */ (function () {
  68672. function MorphTargetManager(scene) {
  68673. if (scene === void 0) { scene = null; }
  68674. this._targets = new Array();
  68675. this._targetObservable = new Array();
  68676. this._activeTargets = new BABYLON.SmartArray(16);
  68677. this._supportsNormals = false;
  68678. this._supportsTangents = false;
  68679. this._vertexCount = 0;
  68680. this._uniqueId = 0;
  68681. this._tempInfluences = new Array();
  68682. if (!scene) {
  68683. scene = BABYLON.Engine.LastCreatedScene;
  68684. }
  68685. this._scene = scene;
  68686. if (this._scene) {
  68687. this._scene.morphTargetManagers.push(this);
  68688. this._uniqueId = this._scene.getUniqueId();
  68689. }
  68690. }
  68691. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  68692. get: function () {
  68693. return this._uniqueId;
  68694. },
  68695. enumerable: true,
  68696. configurable: true
  68697. });
  68698. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  68699. get: function () {
  68700. return this._vertexCount;
  68701. },
  68702. enumerable: true,
  68703. configurable: true
  68704. });
  68705. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  68706. get: function () {
  68707. return this._supportsNormals;
  68708. },
  68709. enumerable: true,
  68710. configurable: true
  68711. });
  68712. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  68713. get: function () {
  68714. return this._supportsTangents;
  68715. },
  68716. enumerable: true,
  68717. configurable: true
  68718. });
  68719. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  68720. get: function () {
  68721. return this._targets.length;
  68722. },
  68723. enumerable: true,
  68724. configurable: true
  68725. });
  68726. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  68727. get: function () {
  68728. return this._activeTargets.length;
  68729. },
  68730. enumerable: true,
  68731. configurable: true
  68732. });
  68733. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  68734. get: function () {
  68735. return this._influences;
  68736. },
  68737. enumerable: true,
  68738. configurable: true
  68739. });
  68740. MorphTargetManager.prototype.getActiveTarget = function (index) {
  68741. return this._activeTargets.data[index];
  68742. };
  68743. MorphTargetManager.prototype.getTarget = function (index) {
  68744. return this._targets[index];
  68745. };
  68746. MorphTargetManager.prototype.addTarget = function (target) {
  68747. var _this = this;
  68748. this._targets.push(target);
  68749. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  68750. _this._syncActiveTargets(needUpdate);
  68751. }));
  68752. this._syncActiveTargets(true);
  68753. };
  68754. MorphTargetManager.prototype.removeTarget = function (target) {
  68755. var index = this._targets.indexOf(target);
  68756. if (index >= 0) {
  68757. this._targets.splice(index, 1);
  68758. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  68759. this._syncActiveTargets(true);
  68760. }
  68761. };
  68762. /**
  68763. * Serializes the current manager into a Serialization object.
  68764. * Returns the serialized object.
  68765. */
  68766. MorphTargetManager.prototype.serialize = function () {
  68767. var serializationObject = {};
  68768. serializationObject.id = this.uniqueId;
  68769. serializationObject.targets = [];
  68770. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68771. var target = _a[_i];
  68772. serializationObject.targets.push(target.serialize());
  68773. }
  68774. return serializationObject;
  68775. };
  68776. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  68777. var influenceCount = 0;
  68778. this._activeTargets.reset();
  68779. this._supportsNormals = true;
  68780. this._supportsTangents = true;
  68781. this._vertexCount = 0;
  68782. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  68783. var target = _a[_i];
  68784. if (target.influence > 0) {
  68785. this._activeTargets.push(target);
  68786. this._tempInfluences[influenceCount++] = target.influence;
  68787. this._supportsNormals = this._supportsNormals && target.hasNormals;
  68788. this._supportsTangents = this._supportsTangents && target.hasTangents;
  68789. var positions = target.getPositions();
  68790. if (!positions) {
  68791. BABYLON.Tools.Error("Invalid target. Target must positions.");
  68792. return;
  68793. }
  68794. var vertexCount = positions.length / 3;
  68795. if (this._vertexCount === 0) {
  68796. this._vertexCount = vertexCount;
  68797. }
  68798. else if (this._vertexCount !== vertexCount) {
  68799. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  68800. return;
  68801. }
  68802. }
  68803. }
  68804. if (!this._influences || this._influences.length !== influenceCount) {
  68805. this._influences = new Float32Array(influenceCount);
  68806. }
  68807. for (var index = 0; index < influenceCount; index++) {
  68808. this._influences[index] = this._tempInfluences[index];
  68809. }
  68810. if (needUpdate && this._scene) {
  68811. // Flag meshes as dirty to resync with the active targets
  68812. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  68813. var mesh = _c[_b];
  68814. if (mesh.morphTargetManager === this) {
  68815. mesh._syncGeometryWithMorphTargetManager();
  68816. }
  68817. }
  68818. }
  68819. };
  68820. // Statics
  68821. MorphTargetManager.Parse = function (serializationObject, scene) {
  68822. var result = new MorphTargetManager(scene);
  68823. result._uniqueId = serializationObject.id;
  68824. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  68825. var targetData = _a[_i];
  68826. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  68827. }
  68828. return result;
  68829. };
  68830. return MorphTargetManager;
  68831. }());
  68832. BABYLON.MorphTargetManager = MorphTargetManager;
  68833. })(BABYLON || (BABYLON = {}));
  68834. //# sourceMappingURL=babylon.morphTargetManager.js.map
  68835. var BABYLON;
  68836. (function (BABYLON) {
  68837. var Octree = /** @class */ (function () {
  68838. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  68839. if (maxDepth === void 0) { maxDepth = 2; }
  68840. this.maxDepth = maxDepth;
  68841. this.dynamicContent = new Array();
  68842. this._maxBlockCapacity = maxBlockCapacity || 64;
  68843. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  68844. this._creationFunc = creationFunc;
  68845. }
  68846. // Methods
  68847. Octree.prototype.update = function (worldMin, worldMax, entries) {
  68848. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  68849. };
  68850. Octree.prototype.addMesh = function (entry) {
  68851. for (var index = 0; index < this.blocks.length; index++) {
  68852. var block = this.blocks[index];
  68853. block.addEntry(entry);
  68854. }
  68855. };
  68856. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  68857. this._selectionContent.reset();
  68858. for (var index = 0; index < this.blocks.length; index++) {
  68859. var block = this.blocks[index];
  68860. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  68861. }
  68862. if (allowDuplicate) {
  68863. this._selectionContent.concat(this.dynamicContent);
  68864. }
  68865. else {
  68866. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68867. }
  68868. return this._selectionContent;
  68869. };
  68870. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  68871. this._selectionContent.reset();
  68872. for (var index = 0; index < this.blocks.length; index++) {
  68873. var block = this.blocks[index];
  68874. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  68875. }
  68876. if (allowDuplicate) {
  68877. this._selectionContent.concat(this.dynamicContent);
  68878. }
  68879. else {
  68880. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68881. }
  68882. return this._selectionContent;
  68883. };
  68884. Octree.prototype.intersectsRay = function (ray) {
  68885. this._selectionContent.reset();
  68886. for (var index = 0; index < this.blocks.length; index++) {
  68887. var block = this.blocks[index];
  68888. block.intersectsRay(ray, this._selectionContent);
  68889. }
  68890. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  68891. return this._selectionContent;
  68892. };
  68893. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  68894. target.blocks = new Array();
  68895. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  68896. // Segmenting space
  68897. for (var x = 0; x < 2; x++) {
  68898. for (var y = 0; y < 2; y++) {
  68899. for (var z = 0; z < 2; z++) {
  68900. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  68901. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  68902. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  68903. block.addEntries(entries);
  68904. target.blocks.push(block);
  68905. }
  68906. }
  68907. }
  68908. };
  68909. Octree.CreationFuncForMeshes = function (entry, block) {
  68910. var boundingInfo = entry.getBoundingInfo();
  68911. if (!entry.isBlocked && boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68912. block.entries.push(entry);
  68913. }
  68914. };
  68915. Octree.CreationFuncForSubMeshes = function (entry, block) {
  68916. var boundingInfo = entry.getBoundingInfo();
  68917. if (boundingInfo && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  68918. block.entries.push(entry);
  68919. }
  68920. };
  68921. return Octree;
  68922. }());
  68923. BABYLON.Octree = Octree;
  68924. })(BABYLON || (BABYLON = {}));
  68925. //# sourceMappingURL=babylon.octree.js.map
  68926. var BABYLON;
  68927. (function (BABYLON) {
  68928. var OctreeBlock = /** @class */ (function () {
  68929. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  68930. this.entries = new Array();
  68931. this._boundingVectors = new Array();
  68932. this._capacity = capacity;
  68933. this._depth = depth;
  68934. this._maxDepth = maxDepth;
  68935. this._creationFunc = creationFunc;
  68936. this._minPoint = minPoint;
  68937. this._maxPoint = maxPoint;
  68938. this._boundingVectors.push(minPoint.clone());
  68939. this._boundingVectors.push(maxPoint.clone());
  68940. this._boundingVectors.push(minPoint.clone());
  68941. this._boundingVectors[2].x = maxPoint.x;
  68942. this._boundingVectors.push(minPoint.clone());
  68943. this._boundingVectors[3].y = maxPoint.y;
  68944. this._boundingVectors.push(minPoint.clone());
  68945. this._boundingVectors[4].z = maxPoint.z;
  68946. this._boundingVectors.push(maxPoint.clone());
  68947. this._boundingVectors[5].z = minPoint.z;
  68948. this._boundingVectors.push(maxPoint.clone());
  68949. this._boundingVectors[6].x = minPoint.x;
  68950. this._boundingVectors.push(maxPoint.clone());
  68951. this._boundingVectors[7].y = minPoint.y;
  68952. }
  68953. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  68954. // Property
  68955. get: function () {
  68956. return this._capacity;
  68957. },
  68958. enumerable: true,
  68959. configurable: true
  68960. });
  68961. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  68962. get: function () {
  68963. return this._minPoint;
  68964. },
  68965. enumerable: true,
  68966. configurable: true
  68967. });
  68968. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  68969. get: function () {
  68970. return this._maxPoint;
  68971. },
  68972. enumerable: true,
  68973. configurable: true
  68974. });
  68975. // Methods
  68976. OctreeBlock.prototype.addEntry = function (entry) {
  68977. if (this.blocks) {
  68978. for (var index = 0; index < this.blocks.length; index++) {
  68979. var block = this.blocks[index];
  68980. block.addEntry(entry);
  68981. }
  68982. return;
  68983. }
  68984. this._creationFunc(entry, this);
  68985. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  68986. this.createInnerBlocks();
  68987. }
  68988. };
  68989. OctreeBlock.prototype.addEntries = function (entries) {
  68990. for (var index = 0; index < entries.length; index++) {
  68991. var mesh = entries[index];
  68992. this.addEntry(mesh);
  68993. }
  68994. };
  68995. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  68996. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  68997. if (this.blocks) {
  68998. for (var index = 0; index < this.blocks.length; index++) {
  68999. var block = this.blocks[index];
  69000. block.select(frustumPlanes, selection, allowDuplicate);
  69001. }
  69002. return;
  69003. }
  69004. if (allowDuplicate) {
  69005. selection.concat(this.entries);
  69006. }
  69007. else {
  69008. selection.concatWithNoDuplicate(this.entries);
  69009. }
  69010. }
  69011. };
  69012. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  69013. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  69014. if (this.blocks) {
  69015. for (var index = 0; index < this.blocks.length; index++) {
  69016. var block = this.blocks[index];
  69017. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  69018. }
  69019. return;
  69020. }
  69021. if (allowDuplicate) {
  69022. selection.concat(this.entries);
  69023. }
  69024. else {
  69025. selection.concatWithNoDuplicate(this.entries);
  69026. }
  69027. }
  69028. };
  69029. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  69030. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  69031. if (this.blocks) {
  69032. for (var index = 0; index < this.blocks.length; index++) {
  69033. var block = this.blocks[index];
  69034. block.intersectsRay(ray, selection);
  69035. }
  69036. return;
  69037. }
  69038. selection.concatWithNoDuplicate(this.entries);
  69039. }
  69040. };
  69041. OctreeBlock.prototype.createInnerBlocks = function () {
  69042. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  69043. };
  69044. return OctreeBlock;
  69045. }());
  69046. BABYLON.OctreeBlock = OctreeBlock;
  69047. })(BABYLON || (BABYLON = {}));
  69048. //# sourceMappingURL=babylon.octreeBlock.js.map
  69049. var BABYLON;
  69050. (function (BABYLON) {
  69051. var SIMDVector3 = /** @class */ (function () {
  69052. function SIMDVector3() {
  69053. }
  69054. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  69055. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  69056. };
  69057. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  69058. var m = transformation.m;
  69059. var m0 = SIMD.Float32x4.load(m, 0);
  69060. var m1 = SIMD.Float32x4.load(m, 4);
  69061. var m2 = SIMD.Float32x4.load(m, 8);
  69062. var m3 = SIMD.Float32x4.load(m, 12);
  69063. 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));
  69064. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  69065. result.x = SIMD.Float32x4.extractLane(r, 0);
  69066. result.y = SIMD.Float32x4.extractLane(r, 1);
  69067. result.z = SIMD.Float32x4.extractLane(r, 2);
  69068. };
  69069. return SIMDVector3;
  69070. }());
  69071. var SIMDMatrix = /** @class */ (function () {
  69072. function SIMDMatrix() {
  69073. }
  69074. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  69075. var tm = this.m;
  69076. var om = other.m;
  69077. var m0 = SIMD.Float32x4.load(om, 0);
  69078. var m1 = SIMD.Float32x4.load(om, 4);
  69079. var m2 = SIMD.Float32x4.load(om, 8);
  69080. var m3 = SIMD.Float32x4.load(om, 12);
  69081. for (var i = 0; i < 16; i += 4) {
  69082. 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)))));
  69083. }
  69084. return this;
  69085. };
  69086. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  69087. var src = this.m;
  69088. var dest = other.m;
  69089. // Load the 4 rows
  69090. var src0 = SIMD.Float32x4.load(src, 0);
  69091. var src1 = SIMD.Float32x4.load(src, 4);
  69092. var src2 = SIMD.Float32x4.load(src, 8);
  69093. var src3 = SIMD.Float32x4.load(src, 12);
  69094. // Transpose the source matrix. Sort of. Not a true transpose operation
  69095. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  69096. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  69097. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  69098. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  69099. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  69100. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  69101. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  69102. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  69103. // This is a true transposition, but it will lead to an incorrect result
  69104. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  69105. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  69106. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  69107. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  69108. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  69109. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  69110. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  69111. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  69112. // ----
  69113. tmp1 = SIMD.Float32x4.mul(row2, row3);
  69114. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69115. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  69116. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  69117. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69118. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  69119. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  69120. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  69121. // ----
  69122. tmp1 = SIMD.Float32x4.mul(row1, row2);
  69123. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69124. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  69125. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  69126. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69127. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  69128. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  69129. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  69130. // ----
  69131. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  69132. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69133. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  69134. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  69135. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  69136. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69137. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  69138. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  69139. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  69140. // ----
  69141. tmp1 = SIMD.Float32x4.mul(row0, row1);
  69142. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69143. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  69144. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  69145. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69146. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  69147. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  69148. // ----
  69149. tmp1 = SIMD.Float32x4.mul(row0, row3);
  69150. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69151. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  69152. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  69153. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69154. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  69155. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  69156. // ----
  69157. tmp1 = SIMD.Float32x4.mul(row0, row2);
  69158. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  69159. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  69160. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  69161. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  69162. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  69163. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  69164. // Compute determinant
  69165. var det = SIMD.Float32x4.mul(row0, minor0);
  69166. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  69167. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  69168. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  69169. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  69170. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  69171. // These shuffles aren't necessary if the faulty transposition is done
  69172. // up at the top of this function.
  69173. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  69174. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  69175. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  69176. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  69177. // Compute final values by multiplying with 1/det
  69178. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  69179. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  69180. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  69181. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  69182. return this;
  69183. };
  69184. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  69185. var out = result.m;
  69186. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  69187. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  69188. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  69189. // cc.kmVec3Subtract(f, pCenter, pEye);
  69190. var f = SIMD.Float32x4.sub(center, eye);
  69191. // cc.kmVec3Normalize(f, f);
  69192. var tmp = SIMD.Float32x4.mul(f, f);
  69193. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69194. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69195. // cc.kmVec3Assign(up, pUp);
  69196. // cc.kmVec3Normalize(up, up);
  69197. tmp = SIMD.Float32x4.mul(up, up);
  69198. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69199. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69200. // cc.kmVec3Cross(s, f, up);
  69201. 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)));
  69202. // cc.kmVec3Normalize(s, s);
  69203. tmp = SIMD.Float32x4.mul(s, s);
  69204. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69205. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69206. // cc.kmVec3Cross(u, s, f);
  69207. 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)));
  69208. // cc.kmVec3Normalize(s, s);
  69209. tmp = SIMD.Float32x4.mul(s, s);
  69210. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  69211. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  69212. var zero = SIMD.Float32x4.splat(0.0);
  69213. s = SIMD.Float32x4.neg(s);
  69214. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  69215. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  69216. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  69217. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  69218. 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);
  69219. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  69220. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  69221. 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)))));
  69222. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  69223. 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)))));
  69224. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  69225. 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)))));
  69226. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  69227. 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)))));
  69228. };
  69229. return SIMDMatrix;
  69230. }());
  69231. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  69232. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  69233. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  69234. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  69235. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  69236. var SIMDHelper = /** @class */ (function () {
  69237. function SIMDHelper() {
  69238. }
  69239. Object.defineProperty(SIMDHelper, "IsEnabled", {
  69240. get: function () {
  69241. return SIMDHelper._isEnabled;
  69242. },
  69243. enumerable: true,
  69244. configurable: true
  69245. });
  69246. SIMDHelper.DisableSIMD = function () {
  69247. // Replace functions
  69248. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  69249. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  69250. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  69251. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  69252. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  69253. SIMDHelper._isEnabled = false;
  69254. };
  69255. SIMDHelper.EnableSIMD = function () {
  69256. if (self.SIMD === undefined) {
  69257. return;
  69258. }
  69259. // check if polyfills needed
  69260. if (!self.Math.fround) {
  69261. self.Math.fround = (function (array) { return function (x) {
  69262. return array[0] = x, array[0];
  69263. }; })(new Float32Array(1));
  69264. }
  69265. if (!self.Math.imul) {
  69266. self.Math.imul = function (a, b) {
  69267. var ah = (a >>> 16) & 0xffff;
  69268. var al = a & 0xffff;
  69269. var bh = (b >>> 16) & 0xffff;
  69270. var bl = b & 0xffff;
  69271. // the shift by 0 fixes the sign on the high part
  69272. // the final |0 converts the unsigned value into a signed value
  69273. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  69274. };
  69275. }
  69276. // Replace functions
  69277. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  69278. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  69279. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  69280. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  69281. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  69282. SIMDHelper._isEnabled = true;
  69283. };
  69284. SIMDHelper._isEnabled = false;
  69285. return SIMDHelper;
  69286. }());
  69287. BABYLON.SIMDHelper = SIMDHelper;
  69288. })(BABYLON || (BABYLON = {}));
  69289. //# sourceMappingURL=babylon.math.SIMD.js.map
  69290. var BABYLON;
  69291. (function (BABYLON) {
  69292. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  69293. __extends(VRDistortionCorrectionPostProcess, _super);
  69294. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  69295. var _this = _super.call(this, name, "vrDistortionCorrection", [
  69296. 'LensCenter',
  69297. 'Scale',
  69298. 'ScaleIn',
  69299. 'HmdWarpParam'
  69300. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  69301. _this._isRightEye = isRightEye;
  69302. _this._distortionFactors = vrMetrics.distortionK;
  69303. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  69304. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  69305. _this.adaptScaleToCurrentViewport = true;
  69306. _this.onSizeChangedObservable.add(function () {
  69307. _this.aspectRatio = _this.width * .5 / _this.height;
  69308. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  69309. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  69310. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  69311. });
  69312. _this.onApplyObservable.add(function (effect) {
  69313. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  69314. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  69315. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  69316. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  69317. });
  69318. return _this;
  69319. }
  69320. return VRDistortionCorrectionPostProcess;
  69321. }(BABYLON.PostProcess));
  69322. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  69323. })(BABYLON || (BABYLON = {}));
  69324. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  69325. var BABYLON;
  69326. (function (BABYLON) {
  69327. var AnaglyphPostProcess = /** @class */ (function (_super) {
  69328. __extends(AnaglyphPostProcess, _super);
  69329. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  69330. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  69331. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69332. _this.onApplyObservable.add(function (effect) {
  69333. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  69334. });
  69335. return _this;
  69336. }
  69337. return AnaglyphPostProcess;
  69338. }(BABYLON.PostProcess));
  69339. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  69340. })(BABYLON || (BABYLON = {}));
  69341. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  69342. var BABYLON;
  69343. (function (BABYLON) {
  69344. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  69345. __extends(StereoscopicInterlacePostProcess, _super);
  69346. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  69347. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  69348. _this._passedProcess = rigCameras[0]._rigPostProcess;
  69349. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69350. _this.onSizeChangedObservable.add(function () {
  69351. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  69352. });
  69353. _this.onApplyObservable.add(function (effect) {
  69354. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  69355. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  69356. });
  69357. return _this;
  69358. }
  69359. return StereoscopicInterlacePostProcess;
  69360. }(BABYLON.PostProcess));
  69361. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  69362. })(BABYLON || (BABYLON = {}));
  69363. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  69364. var BABYLON;
  69365. (function (BABYLON) {
  69366. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  69367. function FreeCameraDeviceOrientationInput() {
  69368. var _this = this;
  69369. this._screenOrientationAngle = 0;
  69370. this._screenQuaternion = new BABYLON.Quaternion();
  69371. this._alpha = 0;
  69372. this._beta = 0;
  69373. this._gamma = 0;
  69374. this._orientationChanged = function () {
  69375. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  69376. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  69377. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  69378. };
  69379. this._deviceOrientation = function (evt) {
  69380. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  69381. _this._beta = evt.beta !== null ? evt.beta : 0;
  69382. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  69383. };
  69384. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  69385. this._orientationChanged();
  69386. }
  69387. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  69388. get: function () {
  69389. return this._camera;
  69390. },
  69391. set: function (camera) {
  69392. this._camera = camera;
  69393. if (this._camera != null && !this._camera.rotationQuaternion) {
  69394. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  69395. }
  69396. },
  69397. enumerable: true,
  69398. configurable: true
  69399. });
  69400. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69401. window.addEventListener("orientationchange", this._orientationChanged);
  69402. window.addEventListener("deviceorientation", this._deviceOrientation);
  69403. //In certain cases, the attach control is called AFTER orientation was changed,
  69404. //So this is needed.
  69405. this._orientationChanged();
  69406. };
  69407. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  69408. window.removeEventListener("orientationchange", this._orientationChanged);
  69409. window.removeEventListener("deviceorientation", this._deviceOrientation);
  69410. };
  69411. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  69412. //if no device orientation provided, don't update the rotation.
  69413. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  69414. if (!this._alpha)
  69415. return;
  69416. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  69417. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  69418. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  69419. //Mirror on XY Plane
  69420. this._camera.rotationQuaternion.z *= -1;
  69421. this._camera.rotationQuaternion.w *= -1;
  69422. };
  69423. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  69424. return "FreeCameraDeviceOrientationInput";
  69425. };
  69426. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  69427. return "deviceOrientation";
  69428. };
  69429. return FreeCameraDeviceOrientationInput;
  69430. }());
  69431. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  69432. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  69433. })(BABYLON || (BABYLON = {}));
  69434. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  69435. var BABYLON;
  69436. (function (BABYLON) {
  69437. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  69438. function ArcRotateCameraVRDeviceOrientationInput() {
  69439. this.alphaCorrection = 1;
  69440. this.betaCorrection = 1;
  69441. this.gammaCorrection = 1;
  69442. this._alpha = 0;
  69443. this._beta = 0;
  69444. this._gamma = 0;
  69445. this._dirty = false;
  69446. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  69447. }
  69448. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  69449. this.camera.attachControl(element, noPreventDefault);
  69450. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  69451. };
  69452. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  69453. if (evt.alpha !== null) {
  69454. this._alpha = +evt.alpha | 0;
  69455. }
  69456. if (evt.beta !== null) {
  69457. this._beta = +evt.beta | 0;
  69458. }
  69459. if (evt.gamma !== null) {
  69460. this._gamma = +evt.gamma | 0;
  69461. }
  69462. this._dirty = true;
  69463. };
  69464. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  69465. if (this._dirty) {
  69466. this._dirty = false;
  69467. if (this._gamma < 0) {
  69468. this._gamma = 180 + this._gamma;
  69469. }
  69470. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  69471. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  69472. }
  69473. };
  69474. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  69475. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  69476. };
  69477. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  69478. return "ArcRotateCameraVRDeviceOrientationInput";
  69479. };
  69480. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  69481. return "VRDeviceOrientation";
  69482. };
  69483. return ArcRotateCameraVRDeviceOrientationInput;
  69484. }());
  69485. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  69486. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  69487. })(BABYLON || (BABYLON = {}));
  69488. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  69489. var BABYLON;
  69490. (function (BABYLON) {
  69491. var VRCameraMetrics = /** @class */ (function () {
  69492. function VRCameraMetrics() {
  69493. this.compensateDistortion = true;
  69494. }
  69495. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  69496. get: function () {
  69497. return this.hResolution / (2 * this.vResolution);
  69498. },
  69499. enumerable: true,
  69500. configurable: true
  69501. });
  69502. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  69503. get: function () {
  69504. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  69505. },
  69506. enumerable: true,
  69507. configurable: true
  69508. });
  69509. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  69510. get: function () {
  69511. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69512. var h = (4 * meters) / this.hScreenSize;
  69513. return BABYLON.Matrix.Translation(h, 0, 0);
  69514. },
  69515. enumerable: true,
  69516. configurable: true
  69517. });
  69518. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  69519. get: function () {
  69520. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  69521. var h = (4 * meters) / this.hScreenSize;
  69522. return BABYLON.Matrix.Translation(-h, 0, 0);
  69523. },
  69524. enumerable: true,
  69525. configurable: true
  69526. });
  69527. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  69528. get: function () {
  69529. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  69530. },
  69531. enumerable: true,
  69532. configurable: true
  69533. });
  69534. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  69535. get: function () {
  69536. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  69537. },
  69538. enumerable: true,
  69539. configurable: true
  69540. });
  69541. VRCameraMetrics.GetDefault = function () {
  69542. var result = new VRCameraMetrics();
  69543. result.hResolution = 1280;
  69544. result.vResolution = 800;
  69545. result.hScreenSize = 0.149759993;
  69546. result.vScreenSize = 0.0935999975;
  69547. result.vScreenCenter = 0.0467999987;
  69548. result.eyeToScreenDistance = 0.0410000011;
  69549. result.lensSeparationDistance = 0.0635000020;
  69550. result.interpupillaryDistance = 0.0640000030;
  69551. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  69552. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  69553. result.postProcessScaleFactor = 1.714605507808412;
  69554. result.lensCenterOffset = 0.151976421;
  69555. return result;
  69556. };
  69557. return VRCameraMetrics;
  69558. }());
  69559. BABYLON.VRCameraMetrics = VRCameraMetrics;
  69560. })(BABYLON || (BABYLON = {}));
  69561. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  69562. var BABYLON;
  69563. (function (BABYLON) {
  69564. var WebVRFreeCamera = /** @class */ (function (_super) {
  69565. __extends(WebVRFreeCamera, _super);
  69566. function WebVRFreeCamera(name, position, scene, webVROptions) {
  69567. if (webVROptions === void 0) { webVROptions = {}; }
  69568. var _this = _super.call(this, name, position, scene) || this;
  69569. _this.webVROptions = webVROptions;
  69570. _this._vrDevice = null;
  69571. _this.rawPose = null;
  69572. _this._specsVersion = "1.1";
  69573. _this._attached = false;
  69574. _this._descendants = [];
  69575. _this.devicePosition = BABYLON.Vector3.Zero();
  69576. _this.deviceScaleFactor = 1;
  69577. _this.controllers = [];
  69578. _this.onControllersAttachedObservable = new BABYLON.Observable();
  69579. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  69580. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  69581. _this.minZ = 0.1;
  69582. //legacy support - the compensation boolean was removed.
  69583. if (arguments.length === 5) {
  69584. _this.webVROptions = arguments[4];
  69585. }
  69586. // default webVR options
  69587. if (_this.webVROptions.trackPosition == undefined) {
  69588. _this.webVROptions.trackPosition = true;
  69589. }
  69590. if (_this.webVROptions.controllerMeshes == undefined) {
  69591. _this.webVROptions.controllerMeshes = true;
  69592. }
  69593. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  69594. _this.webVROptions.defaultLightingOnControllers = true;
  69595. }
  69596. _this.rotationQuaternion = new BABYLON.Quaternion();
  69597. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  69598. if (_this.webVROptions && _this.webVROptions.positionScale) {
  69599. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  69600. }
  69601. //enable VR
  69602. var engine = _this.getEngine();
  69603. _this._onVREnabled = function (success) { if (success) {
  69604. _this.initControllers();
  69605. } };
  69606. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  69607. engine.initWebVR().add(function (event) {
  69608. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  69609. return;
  69610. }
  69611. _this._vrDevice = event.vrDisplay;
  69612. //reset the rig parameters.
  69613. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  69614. if (_this._attached) {
  69615. _this.getEngine().enableVR();
  69616. }
  69617. });
  69618. if (typeof (VRFrameData) !== "undefined")
  69619. _this._frameData = new VRFrameData();
  69620. /**
  69621. * The idea behind the following lines:
  69622. * objects that have the camera as parent should actually have the rig cameras as a parent.
  69623. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  69624. * the second will not show it correctly.
  69625. *
  69626. * To solve this - each object that has the camera as parent will be added to a protected array.
  69627. * When the rig camera renders, it will take this array and set all of those to be its children.
  69628. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  69629. * Amazing!
  69630. */
  69631. scene.onBeforeCameraRenderObservable.add(function (camera) {
  69632. if (camera.parent === _this && _this.rigParenting) {
  69633. _this._descendants = _this.getDescendants(true, function (n) {
  69634. // don't take the cameras or the controllers!
  69635. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  69636. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  69637. return !isController && !isRigCamera;
  69638. });
  69639. _this._descendants.forEach(function (node) {
  69640. node.parent = camera;
  69641. });
  69642. }
  69643. });
  69644. scene.onAfterCameraRenderObservable.add(function (camera) {
  69645. if (camera.parent === _this && _this.rigParenting) {
  69646. _this._descendants.forEach(function (node) {
  69647. node.parent = _this;
  69648. });
  69649. }
  69650. });
  69651. return _this;
  69652. }
  69653. WebVRFreeCamera.prototype.dispose = function () {
  69654. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  69655. _super.prototype.dispose.call(this);
  69656. };
  69657. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  69658. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  69659. var gp = _a[_i];
  69660. if (gp.hand === name) {
  69661. return gp;
  69662. }
  69663. }
  69664. return null;
  69665. };
  69666. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  69667. get: function () {
  69668. if (!this._leftController) {
  69669. this._leftController = this.getControllerByName("left");
  69670. }
  69671. return this._leftController;
  69672. },
  69673. enumerable: true,
  69674. configurable: true
  69675. });
  69676. ;
  69677. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  69678. get: function () {
  69679. if (!this._rightController) {
  69680. this._rightController = this.getControllerByName("right");
  69681. }
  69682. return this._rightController;
  69683. },
  69684. enumerable: true,
  69685. configurable: true
  69686. });
  69687. ;
  69688. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  69689. if (length === void 0) { length = 100; }
  69690. if (this.leftCamera) {
  69691. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  69692. }
  69693. else {
  69694. return _super.prototype.getForwardRay.call(this, length);
  69695. }
  69696. };
  69697. WebVRFreeCamera.prototype._checkInputs = function () {
  69698. if (this._vrDevice && this._vrDevice.isPresenting) {
  69699. this._vrDevice.getFrameData(this._frameData);
  69700. this.updateFromDevice(this._frameData.pose);
  69701. }
  69702. _super.prototype._checkInputs.call(this);
  69703. };
  69704. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  69705. if (poseData && poseData.orientation) {
  69706. this.rawPose = poseData;
  69707. this.deviceRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  69708. if (this.getScene().useRightHandedSystem) {
  69709. this.deviceRotationQuaternion.z *= -1;
  69710. this.deviceRotationQuaternion.w *= -1;
  69711. }
  69712. if (this.webVROptions.trackPosition && this.rawPose.position) {
  69713. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  69714. if (this.getScene().useRightHandedSystem) {
  69715. this.devicePosition.z *= -1;
  69716. }
  69717. }
  69718. }
  69719. };
  69720. /**
  69721. * WebVR's attach control will start broadcasting frames to the device.
  69722. * Note that in certain browsers (chrome for example) this function must be called
  69723. * within a user-interaction callback. Example:
  69724. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  69725. *
  69726. * @param {HTMLElement} element
  69727. * @param {boolean} [noPreventDefault]
  69728. *
  69729. * @memberOf WebVRFreeCamera
  69730. */
  69731. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  69732. _super.prototype.attachControl.call(this, element, noPreventDefault);
  69733. this._attached = true;
  69734. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  69735. if (this._vrDevice) {
  69736. this.getEngine().enableVR();
  69737. }
  69738. };
  69739. WebVRFreeCamera.prototype.detachControl = function (element) {
  69740. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69741. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69742. _super.prototype.detachControl.call(this, element);
  69743. this._attached = false;
  69744. this.getEngine().disableVR();
  69745. };
  69746. WebVRFreeCamera.prototype.getClassName = function () {
  69747. return "WebVRFreeCamera";
  69748. };
  69749. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  69750. //uses the vrDisplay's "resetPose()".
  69751. //pitch and roll won't be affected.
  69752. this._vrDevice.resetPose();
  69753. };
  69754. WebVRFreeCamera.prototype._updateRigCameras = function () {
  69755. var camLeft = this._rigCameras[0];
  69756. var camRight = this._rigCameras[1];
  69757. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69758. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  69759. camLeft.position.copyFrom(this.devicePosition);
  69760. camRight.position.copyFrom(this.devicePosition);
  69761. };
  69762. /**
  69763. * This function is called by the two RIG cameras.
  69764. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  69765. */
  69766. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  69767. var _this = this;
  69768. //WebVR 1.1
  69769. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  69770. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  69771. if (!this.getScene().useRightHandedSystem) {
  69772. [2, 6, 8, 9, 14].forEach(function (num) {
  69773. _this._webvrViewMatrix.m[num] *= -1;
  69774. });
  69775. }
  69776. // update the camera rotation matrix
  69777. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  69778. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  69779. // Computing target and final matrix
  69780. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  69781. var parentCamera = this._cameraRigParams["parentCamera"];
  69782. // should the view matrix be updated with scale and position offset?
  69783. if (parentCamera.deviceScaleFactor !== 1) {
  69784. this._webvrViewMatrix.invert();
  69785. // scale the position, if set
  69786. if (parentCamera.deviceScaleFactor) {
  69787. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  69788. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  69789. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  69790. }
  69791. this._webvrViewMatrix.invert();
  69792. }
  69793. return this._webvrViewMatrix;
  69794. };
  69795. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  69796. var _this = this;
  69797. var parentCamera = this.parent;
  69798. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  69799. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  69800. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  69801. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  69802. //babylon compatible matrix
  69803. if (!this.getScene().useRightHandedSystem) {
  69804. [8, 9, 10, 11].forEach(function (num) {
  69805. _this._projectionMatrix.m[num] *= -1;
  69806. });
  69807. }
  69808. return this._projectionMatrix;
  69809. };
  69810. WebVRFreeCamera.prototype.initControllers = function () {
  69811. var _this = this;
  69812. this.controllers = [];
  69813. var manager = this.getScene().gamepadManager;
  69814. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69815. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69816. var webVrController = gamepad;
  69817. if (webVrController.defaultModel) {
  69818. webVrController.defaultModel.setEnabled(false);
  69819. }
  69820. }
  69821. });
  69822. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69823. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  69824. var webVrController_1 = gamepad;
  69825. if (_this.webVROptions.controllerMeshes) {
  69826. if (webVrController_1.defaultModel) {
  69827. webVrController_1.defaultModel.setEnabled(true);
  69828. }
  69829. else {
  69830. // Load the meshes
  69831. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  69832. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  69833. if (_this.webVROptions.defaultLightingOnControllers) {
  69834. if (!_this._lightOnControllers) {
  69835. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  69836. }
  69837. var activateLightOnSubMeshes_1 = function (mesh, light) {
  69838. var children = mesh.getChildren();
  69839. if (children.length !== 0) {
  69840. children.forEach(function (mesh) {
  69841. light.includedOnlyMeshes.push(mesh);
  69842. activateLightOnSubMeshes_1(mesh, light);
  69843. });
  69844. }
  69845. };
  69846. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  69847. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  69848. }
  69849. });
  69850. }
  69851. }
  69852. webVrController_1.attachToPoseControlledCamera(_this);
  69853. // since this is async - sanity check. Is the controller already stored?
  69854. if (_this.controllers.indexOf(webVrController_1) === -1) {
  69855. //add to the controllers array
  69856. _this.controllers.push(webVrController_1);
  69857. //did we find enough controllers? Great! let the developer know.
  69858. if (_this.controllers.length >= 2) {
  69859. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  69860. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  69861. // So we're overriding setting left & right manually to be sure
  69862. var firstViveWandDetected = false;
  69863. for (var i = 0; i < _this.controllers.length; i++) {
  69864. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  69865. if (!firstViveWandDetected) {
  69866. firstViveWandDetected = true;
  69867. _this.controllers[i].hand = "left";
  69868. }
  69869. else {
  69870. _this.controllers[i].hand = "right";
  69871. }
  69872. }
  69873. }
  69874. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  69875. }
  69876. }
  69877. }
  69878. });
  69879. };
  69880. return WebVRFreeCamera;
  69881. }(BABYLON.FreeCamera));
  69882. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  69883. })(BABYLON || (BABYLON = {}));
  69884. //# sourceMappingURL=babylon.webVRCamera.js.map
  69885. var BABYLON;
  69886. (function (BABYLON) {
  69887. // We're mainly based on the logic defined into the FreeCamera code
  69888. var DeviceOrientationCamera = /** @class */ (function (_super) {
  69889. __extends(DeviceOrientationCamera, _super);
  69890. function DeviceOrientationCamera(name, position, scene) {
  69891. var _this = _super.call(this, name, position, scene) || this;
  69892. _this._quaternionCache = new BABYLON.Quaternion();
  69893. _this.inputs.addDeviceOrientation();
  69894. return _this;
  69895. }
  69896. DeviceOrientationCamera.prototype.getClassName = function () {
  69897. return "DeviceOrientationCamera";
  69898. };
  69899. DeviceOrientationCamera.prototype._checkInputs = function () {
  69900. _super.prototype._checkInputs.call(this);
  69901. this._quaternionCache.copyFrom(this.rotationQuaternion);
  69902. if (this._initialQuaternion) {
  69903. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69904. }
  69905. };
  69906. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  69907. var _this = this;
  69908. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  69909. //can only work if this camera has a rotation quaternion already.
  69910. if (!this.rotationQuaternion)
  69911. return;
  69912. if (!this._initialQuaternion) {
  69913. this._initialQuaternion = new BABYLON.Quaternion();
  69914. }
  69915. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  69916. ['x', 'y', 'z'].forEach(function (axisName) {
  69917. if (!axis[axisName]) {
  69918. _this._initialQuaternion[axisName] = 0;
  69919. }
  69920. else {
  69921. _this._initialQuaternion[axisName] *= -1;
  69922. }
  69923. });
  69924. this._initialQuaternion.normalize();
  69925. //force rotation update
  69926. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  69927. };
  69928. return DeviceOrientationCamera;
  69929. }(BABYLON.FreeCamera));
  69930. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  69931. })(BABYLON || (BABYLON = {}));
  69932. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  69933. var BABYLON;
  69934. (function (BABYLON) {
  69935. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  69936. __extends(VRDeviceOrientationFreeCamera, _super);
  69937. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69938. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69939. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69940. var _this = _super.call(this, name, position, scene) || this;
  69941. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69942. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69943. return _this;
  69944. }
  69945. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  69946. return "VRDeviceOrientationFreeCamera";
  69947. };
  69948. return VRDeviceOrientationFreeCamera;
  69949. }(BABYLON.DeviceOrientationCamera));
  69950. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  69951. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  69952. __extends(VRDeviceOrientationGamepadCamera, _super);
  69953. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  69954. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69955. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69956. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  69957. _this.inputs.addGamepad();
  69958. return _this;
  69959. }
  69960. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  69961. return "VRDeviceOrientationGamepadCamera";
  69962. };
  69963. return VRDeviceOrientationGamepadCamera;
  69964. }(VRDeviceOrientationFreeCamera));
  69965. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  69966. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  69967. __extends(VRDeviceOrientationArcRotateCamera, _super);
  69968. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  69969. if (compensateDistortion === void 0) { compensateDistortion = true; }
  69970. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  69971. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  69972. vrCameraMetrics.compensateDistortion = compensateDistortion;
  69973. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  69974. _this.inputs.addVRDeviceOrientation();
  69975. return _this;
  69976. }
  69977. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  69978. return "VRDeviceOrientationArcRotateCamera";
  69979. };
  69980. return VRDeviceOrientationArcRotateCamera;
  69981. }(BABYLON.ArcRotateCamera));
  69982. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  69983. })(BABYLON || (BABYLON = {}));
  69984. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  69985. var BABYLON;
  69986. (function (BABYLON) {
  69987. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  69988. __extends(AnaglyphFreeCamera, _super);
  69989. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  69990. var _this = _super.call(this, name, position, scene) || this;
  69991. _this.interaxialDistance = interaxialDistance;
  69992. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  69993. return _this;
  69994. }
  69995. AnaglyphFreeCamera.prototype.getClassName = function () {
  69996. return "AnaglyphFreeCamera";
  69997. };
  69998. return AnaglyphFreeCamera;
  69999. }(BABYLON.FreeCamera));
  70000. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  70001. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  70002. __extends(AnaglyphArcRotateCamera, _super);
  70003. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  70004. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70005. _this.interaxialDistance = interaxialDistance;
  70006. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70007. return _this;
  70008. }
  70009. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  70010. return "AnaglyphArcRotateCamera";
  70011. };
  70012. return AnaglyphArcRotateCamera;
  70013. }(BABYLON.ArcRotateCamera));
  70014. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  70015. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  70016. __extends(AnaglyphGamepadCamera, _super);
  70017. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  70018. var _this = _super.call(this, name, position, scene) || this;
  70019. _this.interaxialDistance = interaxialDistance;
  70020. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70021. return _this;
  70022. }
  70023. AnaglyphGamepadCamera.prototype.getClassName = function () {
  70024. return "AnaglyphGamepadCamera";
  70025. };
  70026. return AnaglyphGamepadCamera;
  70027. }(BABYLON.GamepadCamera));
  70028. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  70029. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  70030. __extends(AnaglyphUniversalCamera, _super);
  70031. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  70032. var _this = _super.call(this, name, position, scene) || this;
  70033. _this.interaxialDistance = interaxialDistance;
  70034. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  70035. return _this;
  70036. }
  70037. AnaglyphUniversalCamera.prototype.getClassName = function () {
  70038. return "AnaglyphUniversalCamera";
  70039. };
  70040. return AnaglyphUniversalCamera;
  70041. }(BABYLON.UniversalCamera));
  70042. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  70043. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  70044. __extends(StereoscopicFreeCamera, _super);
  70045. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70046. var _this = _super.call(this, name, position, scene) || this;
  70047. _this.interaxialDistance = interaxialDistance;
  70048. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70049. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70050. return _this;
  70051. }
  70052. StereoscopicFreeCamera.prototype.getClassName = function () {
  70053. return "StereoscopicFreeCamera";
  70054. };
  70055. return StereoscopicFreeCamera;
  70056. }(BABYLON.FreeCamera));
  70057. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  70058. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  70059. __extends(StereoscopicArcRotateCamera, _super);
  70060. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  70061. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  70062. _this.interaxialDistance = interaxialDistance;
  70063. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70064. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70065. return _this;
  70066. }
  70067. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  70068. return "StereoscopicArcRotateCamera";
  70069. };
  70070. return StereoscopicArcRotateCamera;
  70071. }(BABYLON.ArcRotateCamera));
  70072. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  70073. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  70074. __extends(StereoscopicGamepadCamera, _super);
  70075. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70076. var _this = _super.call(this, name, position, scene) || this;
  70077. _this.interaxialDistance = interaxialDistance;
  70078. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70079. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70080. return _this;
  70081. }
  70082. StereoscopicGamepadCamera.prototype.getClassName = function () {
  70083. return "StereoscopicGamepadCamera";
  70084. };
  70085. return StereoscopicGamepadCamera;
  70086. }(BABYLON.GamepadCamera));
  70087. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  70088. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  70089. __extends(StereoscopicUniversalCamera, _super);
  70090. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  70091. var _this = _super.call(this, name, position, scene) || this;
  70092. _this.interaxialDistance = interaxialDistance;
  70093. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  70094. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  70095. return _this;
  70096. }
  70097. StereoscopicUniversalCamera.prototype.getClassName = function () {
  70098. return "StereoscopicUniversalCamera";
  70099. };
  70100. return StereoscopicUniversalCamera;
  70101. }(BABYLON.UniversalCamera));
  70102. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  70103. })(BABYLON || (BABYLON = {}));
  70104. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  70105. var BABYLON;
  70106. (function (BABYLON) {
  70107. var VRExperienceHelper = /** @class */ (function () {
  70108. function VRExperienceHelper(scene, webVROptions) {
  70109. if (webVROptions === void 0) { webVROptions = {}; }
  70110. var _this = this;
  70111. this.webVROptions = webVROptions;
  70112. // Can the system support WebVR, even if a headset isn't plugged in?
  70113. this._webVRsupported = false;
  70114. // If WebVR is supported, is a headset plugged in and are we ready to present?
  70115. this._webVRready = false;
  70116. // Are we waiting for the requestPresent callback to complete?
  70117. this._webVRrequesting = false;
  70118. // Are we presenting to the headset right now?
  70119. this._webVRpresenting = false;
  70120. // Are we presenting in the fullscreen fallback?
  70121. this._fullscreenVRpresenting = false;
  70122. this._scene = scene;
  70123. if (!this._scene.activeCamera || isNaN(this._scene.activeCamera.position.x)) {
  70124. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  70125. }
  70126. else {
  70127. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  70128. if (scene.activeCamera.rotation) {
  70129. this._deviceOrientationCamera.rotation = scene.activeCamera.rotation.clone();
  70130. }
  70131. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  70132. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  70133. }
  70134. this._scene.activeCamera = this._deviceOrientationCamera;
  70135. this._position = this._scene.activeCamera.position;
  70136. this._canvas = scene.getEngine().getRenderingCanvas();
  70137. if (this._canvas) {
  70138. this._scene.activeCamera.attachControl(this._canvas);
  70139. }
  70140. this._btnVR = document.createElement("BUTTON");
  70141. this._btnVR.className = "babylonVRicon";
  70142. this._btnVR.id = "babylonVRiconbtn";
  70143. this._btnVR.title = "Click to switch to VR";
  70144. 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) }";
  70145. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  70146. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  70147. // css += ".babylonVRicon.vrdisplaysupported { }";
  70148. // css += ".babylonVRicon.vrdisplayready { }";
  70149. // css += ".babylonVRicon.vrdisplayrequesting { }";
  70150. var style = document.createElement('style');
  70151. style.appendChild(document.createTextNode(css));
  70152. document.getElementsByTagName('head')[0].appendChild(style);
  70153. if (this._canvas) {
  70154. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70155. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70156. this._btnVR.addEventListener("click", function () {
  70157. _this.enterVR();
  70158. });
  70159. window.addEventListener("resize", function () {
  70160. if (_this._canvas) {
  70161. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  70162. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  70163. }
  70164. if (_this._fullscreenVRpresenting && _this._webVRready) {
  70165. _this.exitVR();
  70166. }
  70167. });
  70168. }
  70169. document.addEventListener("fullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70170. document.addEventListener("mozfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70171. document.addEventListener("webkitfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70172. document.addEventListener("msfullscreenchange", function () { _this._onFullscreenChange(); }, false);
  70173. document.body.appendChild(this._btnVR);
  70174. // Exiting VR mode using 'ESC' key on desktop
  70175. this._onKeyDown = function (event) {
  70176. if (event.keyCode === 27 && _this.isInVRMode()) {
  70177. _this.exitVR();
  70178. }
  70179. };
  70180. document.addEventListener("keydown", this._onKeyDown);
  70181. // Exiting VR mode double tapping the touch screen
  70182. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  70183. if (_this.isInVRMode()) {
  70184. _this.exitVR();
  70185. if (_this._fullscreenVRpresenting) {
  70186. _this._scene.getEngine().switchFullscreen(true);
  70187. }
  70188. }
  70189. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  70190. // Listen for WebVR display changes
  70191. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  70192. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  70193. this._onVRRequestPresentStart = function () {
  70194. _this._webVRrequesting = true;
  70195. _this.updateButtonVisibility();
  70196. };
  70197. this._onVRRequestPresentComplete = function (success) {
  70198. _this._webVRrequesting = false;
  70199. _this.updateButtonVisibility();
  70200. };
  70201. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  70202. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  70203. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  70204. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70205. // Create the cameras
  70206. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  70207. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  70208. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  70209. this.updateButtonVisibility();
  70210. }
  70211. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  70212. if (this.onControllerMeshLoaded) {
  70213. this.onControllerMeshLoaded(webVRController);
  70214. }
  70215. };
  70216. VRExperienceHelper.prototype._onFullscreenChange = function () {
  70217. if (document.fullscreen !== undefined) {
  70218. this._fullscreenVRpresenting = document.fullscreen;
  70219. }
  70220. else if (document.mozFullScreen !== undefined) {
  70221. this._fullscreenVRpresenting = document.mozFullScreen;
  70222. }
  70223. else if (document.webkitIsFullScreen !== undefined) {
  70224. this._fullscreenVRpresenting = document.webkitIsFullScreen;
  70225. }
  70226. else if (document.msIsFullScreen !== undefined) {
  70227. this._fullscreenVRpresenting = document.msIsFullScreen;
  70228. }
  70229. if (!this._fullscreenVRpresenting && this._canvas) {
  70230. this.exitVR();
  70231. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  70232. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  70233. }
  70234. };
  70235. VRExperienceHelper.prototype.isInVRMode = function () {
  70236. return this._webVRpresenting || this._fullscreenVRpresenting;
  70237. };
  70238. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  70239. var vrDisplay = this._scene.getEngine().getVRDevice();
  70240. if (vrDisplay) {
  70241. var wasPresenting = this._webVRpresenting;
  70242. // A VR display is connected
  70243. this._webVRpresenting = vrDisplay.isPresenting;
  70244. if (wasPresenting && !this._webVRpresenting)
  70245. this.exitVR();
  70246. }
  70247. else {
  70248. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  70249. }
  70250. this.updateButtonVisibility();
  70251. };
  70252. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  70253. this._webVRsupported = eventArgs.vrSupported;
  70254. this._webVRready = !!eventArgs.vrDisplay;
  70255. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  70256. this.updateButtonVisibility();
  70257. };
  70258. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  70259. if (!this._btnVR) {
  70260. return;
  70261. }
  70262. this._btnVR.className = "babylonVRicon";
  70263. if (this.isInVRMode()) {
  70264. this._btnVR.className += " vrdisplaypresenting";
  70265. }
  70266. else {
  70267. if (this._webVRready)
  70268. this._btnVR.className += " vrdisplayready";
  70269. if (this._webVRsupported)
  70270. this._btnVR.className += " vrdisplaysupported";
  70271. if (this._webVRrequesting)
  70272. this._btnVR.className += " vrdisplayrequesting";
  70273. }
  70274. };
  70275. /**
  70276. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  70277. * Otherwise, will use the fullscreen API.
  70278. */
  70279. VRExperienceHelper.prototype.enterVR = function () {
  70280. if (this.onEnteringVR) {
  70281. this.onEnteringVR();
  70282. }
  70283. if (this._webVRrequesting)
  70284. return;
  70285. // If WebVR is supported and a headset is connected
  70286. if (this._webVRready) {
  70287. if (!this._webVRpresenting) {
  70288. this._webVRCamera.position = this._position;
  70289. this._scene.activeCamera = this._webVRCamera;
  70290. }
  70291. }
  70292. else {
  70293. this._vrDeviceOrientationCamera.position = this._position;
  70294. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  70295. this._scene.getEngine().switchFullscreen(true);
  70296. this.updateButtonVisibility();
  70297. }
  70298. if (this._scene.activeCamera && this._canvas) {
  70299. this._scene.activeCamera.attachControl(this._canvas);
  70300. }
  70301. };
  70302. /**
  70303. * Attempt to exit VR, or fullscreen.
  70304. */
  70305. VRExperienceHelper.prototype.exitVR = function () {
  70306. if (this.onExitingVR) {
  70307. this.onExitingVR();
  70308. }
  70309. if (this._webVRpresenting) {
  70310. this._scene.getEngine().disableVR();
  70311. }
  70312. if (this._scene.activeCamera) {
  70313. this._position = this._scene.activeCamera.position;
  70314. }
  70315. this._deviceOrientationCamera.position = this._position;
  70316. this._scene.activeCamera = this._deviceOrientationCamera;
  70317. if (this._canvas) {
  70318. this._scene.activeCamera.attachControl(this._canvas);
  70319. }
  70320. this.updateButtonVisibility();
  70321. };
  70322. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  70323. get: function () {
  70324. return this._position;
  70325. },
  70326. set: function (value) {
  70327. this._position = value;
  70328. if (this._scene.activeCamera) {
  70329. this._scene.activeCamera.position = value;
  70330. }
  70331. },
  70332. enumerable: true,
  70333. configurable: true
  70334. });
  70335. VRExperienceHelper.prototype.dispose = function () {
  70336. if (this.isInVRMode()) {
  70337. this.exitVR();
  70338. }
  70339. this._deviceOrientationCamera.dispose();
  70340. if (this._webVRCamera) {
  70341. this._webVRCamera.dispose();
  70342. }
  70343. if (this._vrDeviceOrientationCamera) {
  70344. this._vrDeviceOrientationCamera.dispose();
  70345. }
  70346. document.body.removeChild(this._btnVR);
  70347. document.removeEventListener("keydown", this._onKeyDown);
  70348. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  70349. };
  70350. VRExperienceHelper.prototype.getClassName = function () {
  70351. return "VRExperienceHelper";
  70352. };
  70353. return VRExperienceHelper;
  70354. }());
  70355. BABYLON.VRExperienceHelper = VRExperienceHelper;
  70356. })(BABYLON || (BABYLON = {}));
  70357. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  70358. // Mainly based on these 2 articles :
  70359. // 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
  70360. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  70361. var BABYLON;
  70362. (function (BABYLON) {
  70363. var JoystickAxis;
  70364. (function (JoystickAxis) {
  70365. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  70366. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  70367. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  70368. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  70369. var VirtualJoystick = /** @class */ (function () {
  70370. function VirtualJoystick(leftJoystick) {
  70371. var _this = this;
  70372. if (leftJoystick) {
  70373. this._leftJoystick = true;
  70374. }
  70375. else {
  70376. this._leftJoystick = false;
  70377. }
  70378. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  70379. VirtualJoystick._globalJoystickIndex++;
  70380. // By default left & right arrow keys are moving the X
  70381. // and up & down keys are moving the Y
  70382. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70383. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70384. this.reverseLeftRight = false;
  70385. this.reverseUpDown = false;
  70386. // collections of pointers
  70387. this._touches = new BABYLON.StringDictionary();
  70388. this.deltaPosition = BABYLON.Vector3.Zero();
  70389. this._joystickSensibility = 25;
  70390. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70391. this._rotationSpeed = 25;
  70392. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  70393. this._rotateOnAxisRelativeToMesh = false;
  70394. this._onResize = function (evt) {
  70395. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70396. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70397. if (VirtualJoystick.vjCanvas) {
  70398. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  70399. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  70400. }
  70401. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  70402. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  70403. };
  70404. // injecting a canvas element on top of the canvas 3D game
  70405. if (!VirtualJoystick.vjCanvas) {
  70406. window.addEventListener("resize", this._onResize, false);
  70407. VirtualJoystick.vjCanvas = document.createElement("canvas");
  70408. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  70409. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  70410. VirtualJoystick.vjCanvas.width = window.innerWidth;
  70411. VirtualJoystick.vjCanvas.height = window.innerHeight;
  70412. VirtualJoystick.vjCanvas.style.width = "100%";
  70413. VirtualJoystick.vjCanvas.style.height = "100%";
  70414. VirtualJoystick.vjCanvas.style.position = "absolute";
  70415. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  70416. VirtualJoystick.vjCanvas.style.top = "0px";
  70417. VirtualJoystick.vjCanvas.style.left = "0px";
  70418. VirtualJoystick.vjCanvas.style.zIndex = "5";
  70419. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  70420. // Support for jQuery PEP polyfill
  70421. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  70422. var context = VirtualJoystick.vjCanvas.getContext('2d');
  70423. if (!context) {
  70424. throw new Error("Unable to create canvas for virtual joystick");
  70425. }
  70426. VirtualJoystick.vjCanvasContext = context;
  70427. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  70428. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70429. document.body.appendChild(VirtualJoystick.vjCanvas);
  70430. }
  70431. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  70432. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  70433. this.pressed = false;
  70434. // default joystick color
  70435. this._joystickColor = "cyan";
  70436. this._joystickPointerID = -1;
  70437. // current joystick position
  70438. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  70439. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  70440. // origin joystick position
  70441. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  70442. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  70443. this._onPointerDownHandlerRef = function (evt) {
  70444. _this._onPointerDown(evt);
  70445. };
  70446. this._onPointerMoveHandlerRef = function (evt) {
  70447. _this._onPointerMove(evt);
  70448. };
  70449. this._onPointerOutHandlerRef = function (evt) {
  70450. _this._onPointerUp(evt);
  70451. };
  70452. this._onPointerUpHandlerRef = function (evt) {
  70453. _this._onPointerUp(evt);
  70454. };
  70455. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  70456. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  70457. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  70458. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  70459. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  70460. evt.preventDefault(); // Disables system menu
  70461. }, false);
  70462. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70463. }
  70464. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  70465. this._joystickSensibility = newJoystickSensibility;
  70466. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  70467. };
  70468. VirtualJoystick.prototype._onPointerDown = function (e) {
  70469. var positionOnScreenCondition;
  70470. e.preventDefault();
  70471. if (this._leftJoystick === true) {
  70472. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  70473. }
  70474. else {
  70475. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  70476. }
  70477. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  70478. // First contact will be dedicated to the virtual joystick
  70479. this._joystickPointerID = e.pointerId;
  70480. this._joystickPointerStartPos.x = e.clientX;
  70481. this._joystickPointerStartPos.y = e.clientY;
  70482. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  70483. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  70484. this._deltaJoystickVector.x = 0;
  70485. this._deltaJoystickVector.y = 0;
  70486. this.pressed = true;
  70487. this._touches.add(e.pointerId.toString(), e);
  70488. }
  70489. else {
  70490. // You can only trigger the action buttons with a joystick declared
  70491. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  70492. this._action();
  70493. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  70494. }
  70495. }
  70496. };
  70497. VirtualJoystick.prototype._onPointerMove = function (e) {
  70498. // If the current pointer is the one associated to the joystick (first touch contact)
  70499. if (this._joystickPointerID == e.pointerId) {
  70500. this._joystickPointerPos.x = e.clientX;
  70501. this._joystickPointerPos.y = e.clientY;
  70502. this._deltaJoystickVector = this._joystickPointerPos.clone();
  70503. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  70504. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  70505. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  70506. switch (this._axisTargetedByLeftAndRight) {
  70507. case JoystickAxis.X:
  70508. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  70509. break;
  70510. case JoystickAxis.Y:
  70511. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  70512. break;
  70513. case JoystickAxis.Z:
  70514. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  70515. break;
  70516. }
  70517. var directionUpDown = this.reverseUpDown ? 1 : -1;
  70518. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  70519. switch (this._axisTargetedByUpAndDown) {
  70520. case JoystickAxis.X:
  70521. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  70522. break;
  70523. case JoystickAxis.Y:
  70524. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  70525. break;
  70526. case JoystickAxis.Z:
  70527. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  70528. break;
  70529. }
  70530. }
  70531. else {
  70532. var data = this._touches.get(e.pointerId.toString());
  70533. if (data) {
  70534. data.x = e.clientX;
  70535. data.y = e.clientY;
  70536. }
  70537. }
  70538. };
  70539. VirtualJoystick.prototype._onPointerUp = function (e) {
  70540. if (this._joystickPointerID == e.pointerId) {
  70541. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  70542. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  70543. this._joystickPointerID = -1;
  70544. this.pressed = false;
  70545. }
  70546. else {
  70547. var touch = this._touches.get(e.pointerId.toString());
  70548. if (touch) {
  70549. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70550. }
  70551. }
  70552. this._deltaJoystickVector.x = 0;
  70553. this._deltaJoystickVector.y = 0;
  70554. this._touches.remove(e.pointerId.toString());
  70555. };
  70556. /**
  70557. * Change the color of the virtual joystick
  70558. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  70559. */
  70560. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  70561. this._joystickColor = newColor;
  70562. };
  70563. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  70564. this._action = action;
  70565. };
  70566. // Define which axis you'd like to control for left & right
  70567. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  70568. switch (axis) {
  70569. case JoystickAxis.X:
  70570. case JoystickAxis.Y:
  70571. case JoystickAxis.Z:
  70572. this._axisTargetedByLeftAndRight = axis;
  70573. break;
  70574. default:
  70575. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  70576. break;
  70577. }
  70578. };
  70579. // Define which axis you'd like to control for up & down
  70580. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  70581. switch (axis) {
  70582. case JoystickAxis.X:
  70583. case JoystickAxis.Y:
  70584. case JoystickAxis.Z:
  70585. this._axisTargetedByUpAndDown = axis;
  70586. break;
  70587. default:
  70588. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  70589. break;
  70590. }
  70591. };
  70592. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  70593. var _this = this;
  70594. if (this.pressed) {
  70595. this._touches.forEach(function (key, touch) {
  70596. if (touch.pointerId === _this._joystickPointerID) {
  70597. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  70598. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  70599. VirtualJoystick.vjCanvasContext.beginPath();
  70600. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70601. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70602. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  70603. VirtualJoystick.vjCanvasContext.stroke();
  70604. VirtualJoystick.vjCanvasContext.closePath();
  70605. VirtualJoystick.vjCanvasContext.beginPath();
  70606. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70607. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  70608. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  70609. VirtualJoystick.vjCanvasContext.stroke();
  70610. VirtualJoystick.vjCanvasContext.closePath();
  70611. VirtualJoystick.vjCanvasContext.beginPath();
  70612. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  70613. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  70614. VirtualJoystick.vjCanvasContext.stroke();
  70615. VirtualJoystick.vjCanvasContext.closePath();
  70616. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  70617. }
  70618. else {
  70619. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  70620. VirtualJoystick.vjCanvasContext.beginPath();
  70621. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  70622. VirtualJoystick.vjCanvasContext.beginPath();
  70623. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  70624. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  70625. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  70626. VirtualJoystick.vjCanvasContext.stroke();
  70627. VirtualJoystick.vjCanvasContext.closePath();
  70628. touch.prevX = touch.x;
  70629. touch.prevY = touch.y;
  70630. }
  70631. ;
  70632. });
  70633. }
  70634. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  70635. };
  70636. VirtualJoystick.prototype.releaseCanvas = function () {
  70637. if (VirtualJoystick.vjCanvas) {
  70638. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  70639. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  70640. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  70641. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  70642. window.removeEventListener("resize", this._onResize);
  70643. document.body.removeChild(VirtualJoystick.vjCanvas);
  70644. VirtualJoystick.vjCanvas = null;
  70645. }
  70646. };
  70647. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  70648. VirtualJoystick._globalJoystickIndex = 0;
  70649. return VirtualJoystick;
  70650. }());
  70651. BABYLON.VirtualJoystick = VirtualJoystick;
  70652. })(BABYLON || (BABYLON = {}));
  70653. //# sourceMappingURL=babylon.virtualJoystick.js.map
  70654. var BABYLON;
  70655. (function (BABYLON) {
  70656. // We're mainly based on the logic defined into the FreeCamera code
  70657. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  70658. __extends(VirtualJoysticksCamera, _super);
  70659. function VirtualJoysticksCamera(name, position, scene) {
  70660. var _this = _super.call(this, name, position, scene) || this;
  70661. _this.inputs.addVirtualJoystick();
  70662. return _this;
  70663. }
  70664. VirtualJoysticksCamera.prototype.getClassName = function () {
  70665. return "VirtualJoysticksCamera";
  70666. };
  70667. return VirtualJoysticksCamera;
  70668. }(BABYLON.FreeCamera));
  70669. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  70670. })(BABYLON || (BABYLON = {}));
  70671. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  70672. var BABYLON;
  70673. (function (BABYLON) {
  70674. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  70675. function FreeCameraVirtualJoystickInput() {
  70676. }
  70677. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  70678. return this._leftjoystick;
  70679. };
  70680. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  70681. return this._rightjoystick;
  70682. };
  70683. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  70684. if (this._leftjoystick) {
  70685. var camera = this.camera;
  70686. var speed = camera._computeLocalCameraSpeed() * 50;
  70687. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  70688. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  70689. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  70690. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  70691. if (!this._leftjoystick.pressed) {
  70692. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  70693. }
  70694. if (!this._rightjoystick.pressed) {
  70695. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  70696. }
  70697. }
  70698. };
  70699. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  70700. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  70701. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  70702. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  70703. this._leftjoystick.setJoystickSensibility(0.15);
  70704. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  70705. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  70706. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  70707. this._rightjoystick.reverseUpDown = true;
  70708. this._rightjoystick.setJoystickSensibility(0.05);
  70709. this._rightjoystick.setJoystickColor("yellow");
  70710. };
  70711. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  70712. this._leftjoystick.releaseCanvas();
  70713. this._rightjoystick.releaseCanvas();
  70714. };
  70715. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  70716. return "FreeCameraVirtualJoystickInput";
  70717. };
  70718. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  70719. return "virtualJoystick";
  70720. };
  70721. return FreeCameraVirtualJoystickInput;
  70722. }());
  70723. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  70724. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  70725. })(BABYLON || (BABYLON = {}));
  70726. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  70727. var BABYLON;
  70728. (function (BABYLON) {
  70729. var SimplificationSettings = /** @class */ (function () {
  70730. function SimplificationSettings(quality, distance, optimizeMesh) {
  70731. this.quality = quality;
  70732. this.distance = distance;
  70733. this.optimizeMesh = optimizeMesh;
  70734. }
  70735. return SimplificationSettings;
  70736. }());
  70737. BABYLON.SimplificationSettings = SimplificationSettings;
  70738. var SimplificationQueue = /** @class */ (function () {
  70739. function SimplificationQueue() {
  70740. this.running = false;
  70741. this._simplificationArray = [];
  70742. }
  70743. SimplificationQueue.prototype.addTask = function (task) {
  70744. this._simplificationArray.push(task);
  70745. };
  70746. SimplificationQueue.prototype.executeNext = function () {
  70747. var task = this._simplificationArray.pop();
  70748. if (task) {
  70749. this.running = true;
  70750. this.runSimplification(task);
  70751. }
  70752. else {
  70753. this.running = false;
  70754. }
  70755. };
  70756. SimplificationQueue.prototype.runSimplification = function (task) {
  70757. var _this = this;
  70758. if (task.parallelProcessing) {
  70759. //parallel simplifier
  70760. task.settings.forEach(function (setting) {
  70761. var simplifier = _this.getSimplifier(task);
  70762. simplifier.simplify(setting, function (newMesh) {
  70763. task.mesh.addLODLevel(setting.distance, newMesh);
  70764. newMesh.isVisible = true;
  70765. //check if it is the last
  70766. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  70767. //all done, run the success callback.
  70768. task.successCallback();
  70769. }
  70770. _this.executeNext();
  70771. });
  70772. });
  70773. }
  70774. else {
  70775. //single simplifier.
  70776. var simplifier = this.getSimplifier(task);
  70777. var runDecimation = function (setting, callback) {
  70778. simplifier.simplify(setting, function (newMesh) {
  70779. task.mesh.addLODLevel(setting.distance, newMesh);
  70780. newMesh.isVisible = true;
  70781. //run the next quality level
  70782. callback();
  70783. });
  70784. };
  70785. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  70786. runDecimation(task.settings[loop.index], function () {
  70787. loop.executeNext();
  70788. });
  70789. }, function () {
  70790. //execution ended, run the success callback.
  70791. if (task.successCallback) {
  70792. task.successCallback();
  70793. }
  70794. _this.executeNext();
  70795. });
  70796. }
  70797. };
  70798. SimplificationQueue.prototype.getSimplifier = function (task) {
  70799. switch (task.simplificationType) {
  70800. case SimplificationType.QUADRATIC:
  70801. default:
  70802. return new QuadraticErrorSimplification(task.mesh);
  70803. }
  70804. };
  70805. return SimplificationQueue;
  70806. }());
  70807. BABYLON.SimplificationQueue = SimplificationQueue;
  70808. /**
  70809. * The implemented types of simplification.
  70810. * At the moment only Quadratic Error Decimation is implemented.
  70811. */
  70812. var SimplificationType;
  70813. (function (SimplificationType) {
  70814. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  70815. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  70816. var DecimationTriangle = /** @class */ (function () {
  70817. function DecimationTriangle(vertices) {
  70818. this.vertices = vertices;
  70819. this.error = new Array(4);
  70820. this.deleted = false;
  70821. this.isDirty = false;
  70822. this.deletePending = false;
  70823. this.borderFactor = 0;
  70824. }
  70825. return DecimationTriangle;
  70826. }());
  70827. BABYLON.DecimationTriangle = DecimationTriangle;
  70828. var DecimationVertex = /** @class */ (function () {
  70829. function DecimationVertex(position, id) {
  70830. this.position = position;
  70831. this.id = id;
  70832. this.isBorder = true;
  70833. this.q = new QuadraticMatrix();
  70834. this.triangleCount = 0;
  70835. this.triangleStart = 0;
  70836. this.originalOffsets = [];
  70837. }
  70838. DecimationVertex.prototype.updatePosition = function (newPosition) {
  70839. this.position.copyFrom(newPosition);
  70840. };
  70841. return DecimationVertex;
  70842. }());
  70843. BABYLON.DecimationVertex = DecimationVertex;
  70844. var QuadraticMatrix = /** @class */ (function () {
  70845. function QuadraticMatrix(data) {
  70846. this.data = new Array(10);
  70847. for (var i = 0; i < 10; ++i) {
  70848. if (data && data[i]) {
  70849. this.data[i] = data[i];
  70850. }
  70851. else {
  70852. this.data[i] = 0;
  70853. }
  70854. }
  70855. }
  70856. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  70857. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  70858. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  70859. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  70860. return det;
  70861. };
  70862. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  70863. for (var i = 0; i < 10; ++i) {
  70864. this.data[i] += matrix.data[i];
  70865. }
  70866. };
  70867. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  70868. for (var i = 0; i < 10; ++i) {
  70869. this.data[i] += data[i];
  70870. }
  70871. };
  70872. QuadraticMatrix.prototype.add = function (matrix) {
  70873. var m = new QuadraticMatrix();
  70874. for (var i = 0; i < 10; ++i) {
  70875. m.data[i] = this.data[i] + matrix.data[i];
  70876. }
  70877. return m;
  70878. };
  70879. QuadraticMatrix.FromData = function (a, b, c, d) {
  70880. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  70881. };
  70882. //returning an array to avoid garbage collection
  70883. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  70884. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  70885. };
  70886. return QuadraticMatrix;
  70887. }());
  70888. BABYLON.QuadraticMatrix = QuadraticMatrix;
  70889. var Reference = /** @class */ (function () {
  70890. function Reference(vertexId, triangleId) {
  70891. this.vertexId = vertexId;
  70892. this.triangleId = triangleId;
  70893. }
  70894. return Reference;
  70895. }());
  70896. BABYLON.Reference = Reference;
  70897. /**
  70898. * An implementation of the Quadratic Error simplification algorithm.
  70899. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  70900. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  70901. * @author RaananW
  70902. */
  70903. var QuadraticErrorSimplification = /** @class */ (function () {
  70904. function QuadraticErrorSimplification(_mesh) {
  70905. this._mesh = _mesh;
  70906. this.initialized = false;
  70907. this.syncIterations = 5000;
  70908. this.aggressiveness = 7;
  70909. this.decimationIterations = 100;
  70910. this.boundingBoxEpsilon = BABYLON.Epsilon;
  70911. }
  70912. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  70913. var _this = this;
  70914. this.initDecimatedMesh();
  70915. //iterating through the submeshes array, one after the other.
  70916. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  70917. _this.initWithMesh(loop.index, function () {
  70918. _this.runDecimation(settings, loop.index, function () {
  70919. loop.executeNext();
  70920. });
  70921. }, settings.optimizeMesh);
  70922. }, function () {
  70923. setTimeout(function () {
  70924. successCallback(_this._reconstructedMesh);
  70925. }, 0);
  70926. });
  70927. };
  70928. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  70929. var _this = this;
  70930. var targetCount = ~~(this.triangles.length * settings.quality);
  70931. var deletedTriangles = 0;
  70932. var triangleCount = this.triangles.length;
  70933. var iterationFunction = function (iteration, callback) {
  70934. setTimeout(function () {
  70935. if (iteration % 5 === 0) {
  70936. _this.updateMesh(iteration === 0);
  70937. }
  70938. for (var i = 0; i < _this.triangles.length; ++i) {
  70939. _this.triangles[i].isDirty = false;
  70940. }
  70941. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  70942. var trianglesIterator = function (i) {
  70943. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  70944. var t = _this.triangles[tIdx];
  70945. if (!t)
  70946. return;
  70947. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  70948. return;
  70949. }
  70950. for (var j = 0; j < 3; ++j) {
  70951. if (t.error[j] < threshold) {
  70952. var deleted0 = [];
  70953. var deleted1 = [];
  70954. var v0 = t.vertices[j];
  70955. var v1 = t.vertices[(j + 1) % 3];
  70956. if (v0.isBorder || v1.isBorder)
  70957. continue;
  70958. var p = BABYLON.Vector3.Zero();
  70959. var n = BABYLON.Vector3.Zero();
  70960. var uv = BABYLON.Vector2.Zero();
  70961. var color = new BABYLON.Color4(0, 0, 0, 1);
  70962. _this.calculateError(v0, v1, p, n, uv, color);
  70963. var delTr = new Array();
  70964. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  70965. continue;
  70966. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  70967. continue;
  70968. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  70969. continue;
  70970. var uniqueArray = new Array();
  70971. delTr.forEach(function (deletedT) {
  70972. if (uniqueArray.indexOf(deletedT) === -1) {
  70973. deletedT.deletePending = true;
  70974. uniqueArray.push(deletedT);
  70975. }
  70976. });
  70977. if (uniqueArray.length % 2 !== 0) {
  70978. continue;
  70979. }
  70980. v0.q = v1.q.add(v0.q);
  70981. v0.updatePosition(p);
  70982. var tStart = _this.references.length;
  70983. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  70984. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  70985. var tCount = _this.references.length - tStart;
  70986. if (tCount <= v0.triangleCount) {
  70987. if (tCount) {
  70988. for (var c = 0; c < tCount; c++) {
  70989. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  70990. }
  70991. }
  70992. }
  70993. else {
  70994. v0.triangleStart = tStart;
  70995. }
  70996. v0.triangleCount = tCount;
  70997. break;
  70998. }
  70999. }
  71000. };
  71001. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  71002. }, 0);
  71003. };
  71004. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  71005. if (triangleCount - deletedTriangles <= targetCount)
  71006. loop.breakLoop();
  71007. else {
  71008. iterationFunction(loop.index, function () {
  71009. loop.executeNext();
  71010. });
  71011. }
  71012. }, function () {
  71013. setTimeout(function () {
  71014. //reconstruct this part of the mesh
  71015. _this.reconstructMesh(submeshIndex);
  71016. successCallback();
  71017. }, 0);
  71018. });
  71019. };
  71020. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  71021. var _this = this;
  71022. this.vertices = [];
  71023. this.triangles = [];
  71024. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71025. var indices = this._mesh.getIndices();
  71026. var submesh = this._mesh.subMeshes[submeshIndex];
  71027. var findInVertices = function (positionToSearch) {
  71028. if (optimizeMesh) {
  71029. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  71030. if (_this.vertices[ii].position.equals(positionToSearch)) {
  71031. return _this.vertices[ii];
  71032. }
  71033. }
  71034. }
  71035. return null;
  71036. };
  71037. var vertexReferences = [];
  71038. var vertexInit = function (i) {
  71039. if (!positionData) {
  71040. return;
  71041. }
  71042. var offset = i + submesh.verticesStart;
  71043. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  71044. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  71045. vertex.originalOffsets.push(offset);
  71046. if (vertex.id === _this.vertices.length) {
  71047. _this.vertices.push(vertex);
  71048. }
  71049. vertexReferences.push(vertex.id);
  71050. };
  71051. //var totalVertices = mesh.getTotalVertices();
  71052. var totalVertices = submesh.verticesCount;
  71053. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  71054. var indicesInit = function (i) {
  71055. if (!indices) {
  71056. return;
  71057. }
  71058. var offset = (submesh.indexStart / 3) + i;
  71059. var pos = (offset * 3);
  71060. var i0 = indices[pos + 0];
  71061. var i1 = indices[pos + 1];
  71062. var i2 = indices[pos + 2];
  71063. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  71064. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  71065. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  71066. var triangle = new DecimationTriangle([v0, v1, v2]);
  71067. triangle.originalOffset = pos;
  71068. _this.triangles.push(triangle);
  71069. };
  71070. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  71071. _this.init(callback);
  71072. });
  71073. });
  71074. };
  71075. QuadraticErrorSimplification.prototype.init = function (callback) {
  71076. var _this = this;
  71077. var triangleInit1 = function (i) {
  71078. var t = _this.triangles[i];
  71079. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  71080. for (var j = 0; j < 3; j++) {
  71081. 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))));
  71082. }
  71083. };
  71084. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  71085. var triangleInit2 = function (i) {
  71086. var t = _this.triangles[i];
  71087. for (var j = 0; j < 3; ++j) {
  71088. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  71089. }
  71090. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  71091. };
  71092. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  71093. _this.initialized = true;
  71094. callback();
  71095. });
  71096. });
  71097. };
  71098. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  71099. var newTriangles = [];
  71100. var i;
  71101. for (i = 0; i < this.vertices.length; ++i) {
  71102. this.vertices[i].triangleCount = 0;
  71103. }
  71104. var t;
  71105. var j;
  71106. for (i = 0; i < this.triangles.length; ++i) {
  71107. if (!this.triangles[i].deleted) {
  71108. t = this.triangles[i];
  71109. for (j = 0; j < 3; ++j) {
  71110. t.vertices[j].triangleCount = 1;
  71111. }
  71112. newTriangles.push(t);
  71113. }
  71114. }
  71115. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  71116. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  71117. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  71118. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  71119. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  71120. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  71121. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  71122. var vertexCount = 0;
  71123. for (i = 0; i < this.vertices.length; ++i) {
  71124. var vertex = this.vertices[i];
  71125. vertex.id = vertexCount;
  71126. if (vertex.triangleCount) {
  71127. vertex.originalOffsets.forEach(function (originalOffset) {
  71128. if (!normalData) {
  71129. return;
  71130. }
  71131. newPositionData.push(vertex.position.x);
  71132. newPositionData.push(vertex.position.y);
  71133. newPositionData.push(vertex.position.z);
  71134. newNormalData.push(normalData[originalOffset * 3]);
  71135. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  71136. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  71137. if (uvs && uvs.length) {
  71138. newUVsData.push(uvs[(originalOffset * 2)]);
  71139. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  71140. }
  71141. else if (colorsData && colorsData.length) {
  71142. newColorsData.push(colorsData[(originalOffset * 4)]);
  71143. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  71144. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  71145. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  71146. }
  71147. ++vertexCount;
  71148. });
  71149. }
  71150. }
  71151. var startingIndex = this._reconstructedMesh.getTotalIndices();
  71152. var startingVertex = this._reconstructedMesh.getTotalVertices();
  71153. var submeshesArray = this._reconstructedMesh.subMeshes;
  71154. this._reconstructedMesh.subMeshes = [];
  71155. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  71156. var originalIndices = this._mesh.getIndices();
  71157. for (i = 0; i < newTriangles.length; ++i) {
  71158. t = newTriangles[i]; //now get the new referencing point for each vertex
  71159. [0, 1, 2].forEach(function (idx) {
  71160. var id = originalIndices[t.originalOffset + idx];
  71161. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  71162. if (offset < 0)
  71163. offset = 0;
  71164. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  71165. });
  71166. }
  71167. //overwriting the old vertex buffers and indices.
  71168. this._reconstructedMesh.setIndices(newIndicesArray);
  71169. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  71170. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  71171. if (newUVsData.length > 0)
  71172. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  71173. if (newColorsData.length > 0)
  71174. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  71175. //create submesh
  71176. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  71177. if (submeshIndex > 0) {
  71178. this._reconstructedMesh.subMeshes = [];
  71179. submeshesArray.forEach(function (submesh) {
  71180. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  71181. });
  71182. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  71183. }
  71184. };
  71185. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  71186. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  71187. this._reconstructedMesh.material = this._mesh.material;
  71188. this._reconstructedMesh.parent = this._mesh.parent;
  71189. this._reconstructedMesh.isVisible = false;
  71190. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  71191. };
  71192. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  71193. for (var i = 0; i < vertex1.triangleCount; ++i) {
  71194. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  71195. if (t.deleted)
  71196. continue;
  71197. var s = this.references[vertex1.triangleStart + i].vertexId;
  71198. var v1 = t.vertices[(s + 1) % 3];
  71199. var v2 = t.vertices[(s + 2) % 3];
  71200. if ((v1 === vertex2 || v2 === vertex2)) {
  71201. deletedArray[i] = true;
  71202. delTr.push(t);
  71203. continue;
  71204. }
  71205. var d1 = v1.position.subtract(point);
  71206. d1 = d1.normalize();
  71207. var d2 = v2.position.subtract(point);
  71208. d2 = d2.normalize();
  71209. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  71210. return true;
  71211. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  71212. deletedArray[i] = false;
  71213. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  71214. return true;
  71215. }
  71216. return false;
  71217. };
  71218. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  71219. var newDeleted = deletedTriangles;
  71220. for (var i = 0; i < vertex.triangleCount; ++i) {
  71221. var ref = this.references[vertex.triangleStart + i];
  71222. var t = this.triangles[ref.triangleId];
  71223. if (t.deleted)
  71224. continue;
  71225. if (deletedArray[i] && t.deletePending) {
  71226. t.deleted = true;
  71227. newDeleted++;
  71228. continue;
  71229. }
  71230. t.vertices[ref.vertexId] = origVertex;
  71231. t.isDirty = true;
  71232. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  71233. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  71234. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  71235. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  71236. this.references.push(ref);
  71237. }
  71238. return newDeleted;
  71239. };
  71240. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  71241. for (var i = 0; i < this.vertices.length; ++i) {
  71242. var vCount = [];
  71243. var vId = [];
  71244. var v = this.vertices[i];
  71245. var j;
  71246. for (j = 0; j < v.triangleCount; ++j) {
  71247. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  71248. for (var ii = 0; ii < 3; ii++) {
  71249. var ofs = 0;
  71250. var vv = triangle.vertices[ii];
  71251. while (ofs < vCount.length) {
  71252. if (vId[ofs] === vv.id)
  71253. break;
  71254. ++ofs;
  71255. }
  71256. if (ofs === vCount.length) {
  71257. vCount.push(1);
  71258. vId.push(vv.id);
  71259. }
  71260. else {
  71261. vCount[ofs]++;
  71262. }
  71263. }
  71264. }
  71265. for (j = 0; j < vCount.length; ++j) {
  71266. if (vCount[j] === 1) {
  71267. this.vertices[vId[j]].isBorder = true;
  71268. }
  71269. else {
  71270. this.vertices[vId[j]].isBorder = false;
  71271. }
  71272. }
  71273. }
  71274. };
  71275. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  71276. if (identifyBorders === void 0) { identifyBorders = false; }
  71277. var i;
  71278. if (!identifyBorders) {
  71279. var newTrianglesVector = [];
  71280. for (i = 0; i < this.triangles.length; ++i) {
  71281. if (!this.triangles[i].deleted) {
  71282. newTrianglesVector.push(this.triangles[i]);
  71283. }
  71284. }
  71285. this.triangles = newTrianglesVector;
  71286. }
  71287. for (i = 0; i < this.vertices.length; ++i) {
  71288. this.vertices[i].triangleCount = 0;
  71289. this.vertices[i].triangleStart = 0;
  71290. }
  71291. var t;
  71292. var j;
  71293. var v;
  71294. for (i = 0; i < this.triangles.length; ++i) {
  71295. t = this.triangles[i];
  71296. for (j = 0; j < 3; ++j) {
  71297. v = t.vertices[j];
  71298. v.triangleCount++;
  71299. }
  71300. }
  71301. var tStart = 0;
  71302. for (i = 0; i < this.vertices.length; ++i) {
  71303. this.vertices[i].triangleStart = tStart;
  71304. tStart += this.vertices[i].triangleCount;
  71305. this.vertices[i].triangleCount = 0;
  71306. }
  71307. var newReferences = new Array(this.triangles.length * 3);
  71308. for (i = 0; i < this.triangles.length; ++i) {
  71309. t = this.triangles[i];
  71310. for (j = 0; j < 3; ++j) {
  71311. v = t.vertices[j];
  71312. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  71313. v.triangleCount++;
  71314. }
  71315. }
  71316. this.references = newReferences;
  71317. if (identifyBorders) {
  71318. this.identifyBorder();
  71319. }
  71320. };
  71321. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  71322. var x = point.x;
  71323. var y = point.y;
  71324. var z = point.z;
  71325. 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
  71326. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  71327. };
  71328. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  71329. var q = vertex1.q.add(vertex2.q);
  71330. var border = vertex1.isBorder && vertex2.isBorder;
  71331. var error = 0;
  71332. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  71333. if (qDet !== 0 && !border) {
  71334. if (!pointResult) {
  71335. pointResult = BABYLON.Vector3.Zero();
  71336. }
  71337. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  71338. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  71339. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  71340. error = this.vertexError(q, pointResult);
  71341. }
  71342. else {
  71343. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  71344. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  71345. var error1 = this.vertexError(q, vertex1.position);
  71346. var error2 = this.vertexError(q, vertex2.position);
  71347. var error3 = this.vertexError(q, p3);
  71348. error = Math.min(error1, error2, error3);
  71349. if (error === error1) {
  71350. if (pointResult) {
  71351. pointResult.copyFrom(vertex1.position);
  71352. }
  71353. }
  71354. else if (error === error2) {
  71355. if (pointResult) {
  71356. pointResult.copyFrom(vertex2.position);
  71357. }
  71358. }
  71359. else {
  71360. if (pointResult) {
  71361. pointResult.copyFrom(p3);
  71362. }
  71363. }
  71364. }
  71365. return error;
  71366. };
  71367. return QuadraticErrorSimplification;
  71368. }());
  71369. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  71370. })(BABYLON || (BABYLON = {}));
  71371. //# sourceMappingURL=babylon.meshSimplification.js.map
  71372. var BABYLON;
  71373. (function (BABYLON) {
  71374. var Internals;
  71375. (function (Internals) {
  71376. var MeshLODLevel = /** @class */ (function () {
  71377. function MeshLODLevel(distance, mesh) {
  71378. this.distance = distance;
  71379. this.mesh = mesh;
  71380. }
  71381. return MeshLODLevel;
  71382. }());
  71383. Internals.MeshLODLevel = MeshLODLevel;
  71384. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  71385. })(BABYLON || (BABYLON = {}));
  71386. //# sourceMappingURL=babylon.meshLODLevel.js.map
  71387. var BABYLON;
  71388. (function (BABYLON) {
  71389. // Standard optimizations
  71390. var SceneOptimization = /** @class */ (function () {
  71391. function SceneOptimization(priority) {
  71392. if (priority === void 0) { priority = 0; }
  71393. this.priority = priority;
  71394. this.apply = function (scene) {
  71395. return true; // Return true if everything that can be done was applied
  71396. };
  71397. }
  71398. return SceneOptimization;
  71399. }());
  71400. BABYLON.SceneOptimization = SceneOptimization;
  71401. var TextureOptimization = /** @class */ (function (_super) {
  71402. __extends(TextureOptimization, _super);
  71403. function TextureOptimization(priority, maximumSize) {
  71404. if (priority === void 0) { priority = 0; }
  71405. if (maximumSize === void 0) { maximumSize = 1024; }
  71406. var _this = _super.call(this, priority) || this;
  71407. _this.priority = priority;
  71408. _this.maximumSize = maximumSize;
  71409. _this.apply = function (scene) {
  71410. var allDone = true;
  71411. for (var index = 0; index < scene.textures.length; index++) {
  71412. var texture = scene.textures[index];
  71413. if (!texture.canRescale || texture.getContext) {
  71414. continue;
  71415. }
  71416. var currentSize = texture.getSize();
  71417. var maxDimension = Math.max(currentSize.width, currentSize.height);
  71418. if (maxDimension > _this.maximumSize) {
  71419. texture.scale(0.5);
  71420. allDone = false;
  71421. }
  71422. }
  71423. return allDone;
  71424. };
  71425. return _this;
  71426. }
  71427. return TextureOptimization;
  71428. }(SceneOptimization));
  71429. BABYLON.TextureOptimization = TextureOptimization;
  71430. var HardwareScalingOptimization = /** @class */ (function (_super) {
  71431. __extends(HardwareScalingOptimization, _super);
  71432. function HardwareScalingOptimization(priority, maximumScale) {
  71433. if (priority === void 0) { priority = 0; }
  71434. if (maximumScale === void 0) { maximumScale = 2; }
  71435. var _this = _super.call(this, priority) || this;
  71436. _this.priority = priority;
  71437. _this.maximumScale = maximumScale;
  71438. _this._currentScale = 1;
  71439. _this.apply = function (scene) {
  71440. _this._currentScale++;
  71441. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  71442. return _this._currentScale >= _this.maximumScale;
  71443. };
  71444. return _this;
  71445. }
  71446. return HardwareScalingOptimization;
  71447. }(SceneOptimization));
  71448. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  71449. var ShadowsOptimization = /** @class */ (function (_super) {
  71450. __extends(ShadowsOptimization, _super);
  71451. function ShadowsOptimization() {
  71452. var _this = _super !== null && _super.apply(this, arguments) || this;
  71453. _this.apply = function (scene) {
  71454. scene.shadowsEnabled = false;
  71455. return true;
  71456. };
  71457. return _this;
  71458. }
  71459. return ShadowsOptimization;
  71460. }(SceneOptimization));
  71461. BABYLON.ShadowsOptimization = ShadowsOptimization;
  71462. var PostProcessesOptimization = /** @class */ (function (_super) {
  71463. __extends(PostProcessesOptimization, _super);
  71464. function PostProcessesOptimization() {
  71465. var _this = _super !== null && _super.apply(this, arguments) || this;
  71466. _this.apply = function (scene) {
  71467. scene.postProcessesEnabled = false;
  71468. return true;
  71469. };
  71470. return _this;
  71471. }
  71472. return PostProcessesOptimization;
  71473. }(SceneOptimization));
  71474. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  71475. var LensFlaresOptimization = /** @class */ (function (_super) {
  71476. __extends(LensFlaresOptimization, _super);
  71477. function LensFlaresOptimization() {
  71478. var _this = _super !== null && _super.apply(this, arguments) || this;
  71479. _this.apply = function (scene) {
  71480. scene.lensFlaresEnabled = false;
  71481. return true;
  71482. };
  71483. return _this;
  71484. }
  71485. return LensFlaresOptimization;
  71486. }(SceneOptimization));
  71487. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  71488. var ParticlesOptimization = /** @class */ (function (_super) {
  71489. __extends(ParticlesOptimization, _super);
  71490. function ParticlesOptimization() {
  71491. var _this = _super !== null && _super.apply(this, arguments) || this;
  71492. _this.apply = function (scene) {
  71493. scene.particlesEnabled = false;
  71494. return true;
  71495. };
  71496. return _this;
  71497. }
  71498. return ParticlesOptimization;
  71499. }(SceneOptimization));
  71500. BABYLON.ParticlesOptimization = ParticlesOptimization;
  71501. var RenderTargetsOptimization = /** @class */ (function (_super) {
  71502. __extends(RenderTargetsOptimization, _super);
  71503. function RenderTargetsOptimization() {
  71504. var _this = _super !== null && _super.apply(this, arguments) || this;
  71505. _this.apply = function (scene) {
  71506. scene.renderTargetsEnabled = false;
  71507. return true;
  71508. };
  71509. return _this;
  71510. }
  71511. return RenderTargetsOptimization;
  71512. }(SceneOptimization));
  71513. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  71514. var MergeMeshesOptimization = /** @class */ (function (_super) {
  71515. __extends(MergeMeshesOptimization, _super);
  71516. function MergeMeshesOptimization() {
  71517. var _this = _super !== null && _super.apply(this, arguments) || this;
  71518. _this._canBeMerged = function (abstractMesh) {
  71519. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  71520. return false;
  71521. }
  71522. var mesh = abstractMesh;
  71523. if (!mesh.isVisible || !mesh.isEnabled()) {
  71524. return false;
  71525. }
  71526. if (mesh.instances.length > 0) {
  71527. return false;
  71528. }
  71529. if (mesh.skeleton || mesh.hasLODLevels) {
  71530. return false;
  71531. }
  71532. if (mesh.parent) {
  71533. return false;
  71534. }
  71535. return true;
  71536. };
  71537. _this.apply = function (scene, updateSelectionTree) {
  71538. var globalPool = scene.meshes.slice(0);
  71539. var globalLength = globalPool.length;
  71540. for (var index = 0; index < globalLength; index++) {
  71541. var currentPool = new Array();
  71542. var current = globalPool[index];
  71543. // Checks
  71544. if (!_this._canBeMerged(current)) {
  71545. continue;
  71546. }
  71547. currentPool.push(current);
  71548. // Find compatible meshes
  71549. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  71550. var otherMesh = globalPool[subIndex];
  71551. if (!_this._canBeMerged(otherMesh)) {
  71552. continue;
  71553. }
  71554. if (otherMesh.material !== current.material) {
  71555. continue;
  71556. }
  71557. if (otherMesh.checkCollisions !== current.checkCollisions) {
  71558. continue;
  71559. }
  71560. currentPool.push(otherMesh);
  71561. globalLength--;
  71562. globalPool.splice(subIndex, 1);
  71563. subIndex--;
  71564. }
  71565. if (currentPool.length < 2) {
  71566. continue;
  71567. }
  71568. // Merge meshes
  71569. BABYLON.Mesh.MergeMeshes(currentPool);
  71570. }
  71571. if (updateSelectionTree != undefined) {
  71572. if (updateSelectionTree) {
  71573. scene.createOrUpdateSelectionOctree();
  71574. }
  71575. }
  71576. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  71577. scene.createOrUpdateSelectionOctree();
  71578. }
  71579. return true;
  71580. };
  71581. return _this;
  71582. }
  71583. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  71584. get: function () {
  71585. return MergeMeshesOptimization._UpdateSelectionTree;
  71586. },
  71587. set: function (value) {
  71588. MergeMeshesOptimization._UpdateSelectionTree = value;
  71589. },
  71590. enumerable: true,
  71591. configurable: true
  71592. });
  71593. MergeMeshesOptimization._UpdateSelectionTree = false;
  71594. return MergeMeshesOptimization;
  71595. }(SceneOptimization));
  71596. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  71597. // Options
  71598. var SceneOptimizerOptions = /** @class */ (function () {
  71599. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  71600. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  71601. if (trackerDuration === void 0) { trackerDuration = 2000; }
  71602. this.targetFrameRate = targetFrameRate;
  71603. this.trackerDuration = trackerDuration;
  71604. this.optimizations = new Array();
  71605. }
  71606. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  71607. var result = new SceneOptimizerOptions(targetFrameRate);
  71608. var priority = 0;
  71609. result.optimizations.push(new MergeMeshesOptimization(priority));
  71610. result.optimizations.push(new ShadowsOptimization(priority));
  71611. result.optimizations.push(new LensFlaresOptimization(priority));
  71612. // Next priority
  71613. priority++;
  71614. result.optimizations.push(new PostProcessesOptimization(priority));
  71615. result.optimizations.push(new ParticlesOptimization(priority));
  71616. // Next priority
  71617. priority++;
  71618. result.optimizations.push(new TextureOptimization(priority, 1024));
  71619. return result;
  71620. };
  71621. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  71622. var result = new SceneOptimizerOptions(targetFrameRate);
  71623. var priority = 0;
  71624. result.optimizations.push(new MergeMeshesOptimization(priority));
  71625. result.optimizations.push(new ShadowsOptimization(priority));
  71626. result.optimizations.push(new LensFlaresOptimization(priority));
  71627. // Next priority
  71628. priority++;
  71629. result.optimizations.push(new PostProcessesOptimization(priority));
  71630. result.optimizations.push(new ParticlesOptimization(priority));
  71631. // Next priority
  71632. priority++;
  71633. result.optimizations.push(new TextureOptimization(priority, 512));
  71634. // Next priority
  71635. priority++;
  71636. result.optimizations.push(new RenderTargetsOptimization(priority));
  71637. // Next priority
  71638. priority++;
  71639. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  71640. return result;
  71641. };
  71642. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  71643. var result = new SceneOptimizerOptions(targetFrameRate);
  71644. var priority = 0;
  71645. result.optimizations.push(new MergeMeshesOptimization(priority));
  71646. result.optimizations.push(new ShadowsOptimization(priority));
  71647. result.optimizations.push(new LensFlaresOptimization(priority));
  71648. // Next priority
  71649. priority++;
  71650. result.optimizations.push(new PostProcessesOptimization(priority));
  71651. result.optimizations.push(new ParticlesOptimization(priority));
  71652. // Next priority
  71653. priority++;
  71654. result.optimizations.push(new TextureOptimization(priority, 256));
  71655. // Next priority
  71656. priority++;
  71657. result.optimizations.push(new RenderTargetsOptimization(priority));
  71658. // Next priority
  71659. priority++;
  71660. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  71661. return result;
  71662. };
  71663. return SceneOptimizerOptions;
  71664. }());
  71665. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  71666. // Scene optimizer tool
  71667. var SceneOptimizer = /** @class */ (function () {
  71668. function SceneOptimizer() {
  71669. }
  71670. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  71671. // TODO: add an epsilon
  71672. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  71673. if (onSuccess) {
  71674. onSuccess();
  71675. }
  71676. return;
  71677. }
  71678. // Apply current level of optimizations
  71679. var allDone = true;
  71680. var noOptimizationApplied = true;
  71681. for (var index = 0; index < options.optimizations.length; index++) {
  71682. var optimization = options.optimizations[index];
  71683. if (optimization.priority === currentPriorityLevel) {
  71684. noOptimizationApplied = false;
  71685. allDone = allDone && optimization.apply(scene);
  71686. }
  71687. }
  71688. // If no optimization was applied, this is a failure :(
  71689. if (noOptimizationApplied) {
  71690. if (onFailure) {
  71691. onFailure();
  71692. }
  71693. return;
  71694. }
  71695. // If all optimizations were done, move to next level
  71696. if (allDone) {
  71697. currentPriorityLevel++;
  71698. }
  71699. // Let's the system running for a specific amount of time before checking FPS
  71700. scene.executeWhenReady(function () {
  71701. setTimeout(function () {
  71702. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  71703. }, options.trackerDuration);
  71704. });
  71705. };
  71706. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  71707. if (!options) {
  71708. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  71709. }
  71710. // Let's the system running for a specific amount of time before checking FPS
  71711. scene.executeWhenReady(function () {
  71712. setTimeout(function () {
  71713. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  71714. }, options.trackerDuration);
  71715. });
  71716. };
  71717. return SceneOptimizer;
  71718. }());
  71719. BABYLON.SceneOptimizer = SceneOptimizer;
  71720. })(BABYLON || (BABYLON = {}));
  71721. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  71722. var BABYLON;
  71723. (function (BABYLON) {
  71724. var OutlineRenderer = /** @class */ (function () {
  71725. function OutlineRenderer(scene) {
  71726. this.zOffset = 1;
  71727. this._scene = scene;
  71728. }
  71729. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  71730. var _this = this;
  71731. if (useOverlay === void 0) { useOverlay = false; }
  71732. var scene = this._scene;
  71733. var engine = this._scene.getEngine();
  71734. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  71735. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  71736. return;
  71737. }
  71738. var mesh = subMesh.getRenderingMesh();
  71739. var material = subMesh.getMaterial();
  71740. if (!material || !scene.activeCamera) {
  71741. return;
  71742. }
  71743. engine.enableEffect(this._effect);
  71744. // Logarithmic depth
  71745. if (material.useLogarithmicDepth) {
  71746. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  71747. }
  71748. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  71749. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  71750. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71751. // Bones
  71752. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71753. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71754. }
  71755. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  71756. // Alpha test
  71757. if (material && material.needAlphaTesting()) {
  71758. var alphaTexture = material.getAlphaTestTexture();
  71759. if (alphaTexture) {
  71760. this._effect.setTexture("diffuseSampler", alphaTexture);
  71761. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71762. }
  71763. }
  71764. engine.setZOffset(-this.zOffset);
  71765. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  71766. engine.setZOffset(0);
  71767. };
  71768. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  71769. var defines = [];
  71770. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  71771. var mesh = subMesh.getMesh();
  71772. var material = subMesh.getMaterial();
  71773. if (material) {
  71774. // Alpha test
  71775. if (material.needAlphaTesting()) {
  71776. defines.push("#define ALPHATEST");
  71777. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71778. attribs.push(BABYLON.VertexBuffer.UVKind);
  71779. defines.push("#define UV1");
  71780. }
  71781. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71782. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71783. defines.push("#define UV2");
  71784. }
  71785. }
  71786. //Logarithmic depth
  71787. if (material.useLogarithmicDepth) {
  71788. defines.push("#define LOGARITHMICDEPTH");
  71789. }
  71790. }
  71791. // Bones
  71792. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71793. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71794. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71795. if (mesh.numBoneInfluencers > 4) {
  71796. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  71797. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  71798. }
  71799. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71800. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  71801. }
  71802. else {
  71803. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71804. }
  71805. // Instances
  71806. if (useInstances) {
  71807. defines.push("#define INSTANCES");
  71808. attribs.push("world0");
  71809. attribs.push("world1");
  71810. attribs.push("world2");
  71811. attribs.push("world3");
  71812. }
  71813. // Get correct effect
  71814. var join = defines.join("\n");
  71815. if (this._cachedDefines !== join) {
  71816. this._cachedDefines = join;
  71817. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  71818. }
  71819. return this._effect.isReady();
  71820. };
  71821. return OutlineRenderer;
  71822. }());
  71823. BABYLON.OutlineRenderer = OutlineRenderer;
  71824. })(BABYLON || (BABYLON = {}));
  71825. //# sourceMappingURL=babylon.outlineRenderer.js.map
  71826. var BABYLON;
  71827. (function (BABYLON) {
  71828. var FaceAdjacencies = /** @class */ (function () {
  71829. function FaceAdjacencies() {
  71830. this.edges = new Array();
  71831. this.edgesConnectedCount = 0;
  71832. }
  71833. return FaceAdjacencies;
  71834. }());
  71835. var EdgesRenderer = /** @class */ (function () {
  71836. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  71837. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  71838. if (epsilon === void 0) { epsilon = 0.95; }
  71839. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  71840. this.edgesWidthScalerForOrthographic = 1000.0;
  71841. this.edgesWidthScalerForPerspective = 50.0;
  71842. this._linesPositions = new Array();
  71843. this._linesNormals = new Array();
  71844. this._linesIndices = new Array();
  71845. this._buffers = {};
  71846. this._checkVerticesInsteadOfIndices = false;
  71847. this._source = source;
  71848. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  71849. this._epsilon = epsilon;
  71850. this._prepareRessources();
  71851. this._generateEdgesLines();
  71852. }
  71853. EdgesRenderer.prototype._prepareRessources = function () {
  71854. if (this._lineShader) {
  71855. return;
  71856. }
  71857. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  71858. attributes: ["position", "normal"],
  71859. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  71860. });
  71861. this._lineShader.disableDepthWrite = true;
  71862. this._lineShader.backFaceCulling = false;
  71863. };
  71864. EdgesRenderer.prototype._rebuild = function () {
  71865. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71866. if (buffer) {
  71867. buffer._rebuild();
  71868. }
  71869. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71870. if (buffer) {
  71871. buffer._rebuild();
  71872. }
  71873. var scene = this._source.getScene();
  71874. var engine = scene.getEngine();
  71875. this._ib = engine.createIndexBuffer(this._linesIndices);
  71876. };
  71877. EdgesRenderer.prototype.dispose = function () {
  71878. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  71879. if (buffer) {
  71880. buffer.dispose();
  71881. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  71882. }
  71883. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  71884. if (buffer) {
  71885. buffer.dispose();
  71886. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  71887. }
  71888. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  71889. this._lineShader.dispose();
  71890. };
  71891. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  71892. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  71893. return 0;
  71894. }
  71895. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  71896. return 1;
  71897. }
  71898. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  71899. return 2;
  71900. }
  71901. return -1;
  71902. };
  71903. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  71904. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  71905. return 0;
  71906. }
  71907. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  71908. return 1;
  71909. }
  71910. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  71911. return 2;
  71912. }
  71913. return -1;
  71914. };
  71915. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  71916. var needToCreateLine;
  71917. if (edge === undefined) {
  71918. needToCreateLine = true;
  71919. }
  71920. else {
  71921. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  71922. needToCreateLine = dotProduct < this._epsilon;
  71923. }
  71924. if (needToCreateLine) {
  71925. var offset = this._linesPositions.length / 3;
  71926. var normal = p0.subtract(p1);
  71927. normal.normalize();
  71928. // Positions
  71929. this._linesPositions.push(p0.x);
  71930. this._linesPositions.push(p0.y);
  71931. this._linesPositions.push(p0.z);
  71932. this._linesPositions.push(p0.x);
  71933. this._linesPositions.push(p0.y);
  71934. this._linesPositions.push(p0.z);
  71935. this._linesPositions.push(p1.x);
  71936. this._linesPositions.push(p1.y);
  71937. this._linesPositions.push(p1.z);
  71938. this._linesPositions.push(p1.x);
  71939. this._linesPositions.push(p1.y);
  71940. this._linesPositions.push(p1.z);
  71941. // Normals
  71942. this._linesNormals.push(p1.x);
  71943. this._linesNormals.push(p1.y);
  71944. this._linesNormals.push(p1.z);
  71945. this._linesNormals.push(-1);
  71946. this._linesNormals.push(p1.x);
  71947. this._linesNormals.push(p1.y);
  71948. this._linesNormals.push(p1.z);
  71949. this._linesNormals.push(1);
  71950. this._linesNormals.push(p0.x);
  71951. this._linesNormals.push(p0.y);
  71952. this._linesNormals.push(p0.z);
  71953. this._linesNormals.push(-1);
  71954. this._linesNormals.push(p0.x);
  71955. this._linesNormals.push(p0.y);
  71956. this._linesNormals.push(p0.z);
  71957. this._linesNormals.push(1);
  71958. // Indices
  71959. this._linesIndices.push(offset);
  71960. this._linesIndices.push(offset + 1);
  71961. this._linesIndices.push(offset + 2);
  71962. this._linesIndices.push(offset);
  71963. this._linesIndices.push(offset + 2);
  71964. this._linesIndices.push(offset + 3);
  71965. }
  71966. };
  71967. EdgesRenderer.prototype._generateEdgesLines = function () {
  71968. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  71969. var indices = this._source.getIndices();
  71970. if (!indices || !positions) {
  71971. return;
  71972. }
  71973. // First let's find adjacencies
  71974. var adjacencies = new Array();
  71975. var faceNormals = new Array();
  71976. var index;
  71977. var faceAdjacencies;
  71978. // Prepare faces
  71979. for (index = 0; index < indices.length; index += 3) {
  71980. faceAdjacencies = new FaceAdjacencies();
  71981. var p0Index = indices[index];
  71982. var p1Index = indices[index + 1];
  71983. var p2Index = indices[index + 2];
  71984. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  71985. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  71986. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  71987. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  71988. faceNormal.normalize();
  71989. faceNormals.push(faceNormal);
  71990. adjacencies.push(faceAdjacencies);
  71991. }
  71992. // Scan
  71993. for (index = 0; index < adjacencies.length; index++) {
  71994. faceAdjacencies = adjacencies[index];
  71995. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  71996. var otherFaceAdjacencies = adjacencies[otherIndex];
  71997. if (faceAdjacencies.edgesConnectedCount === 3) {
  71998. break;
  71999. }
  72000. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  72001. continue;
  72002. }
  72003. var otherP0 = indices[otherIndex * 3];
  72004. var otherP1 = indices[otherIndex * 3 + 1];
  72005. var otherP2 = indices[otherIndex * 3 + 2];
  72006. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  72007. var otherEdgeIndex = 0;
  72008. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  72009. continue;
  72010. }
  72011. switch (edgeIndex) {
  72012. case 0:
  72013. if (this._checkVerticesInsteadOfIndices) {
  72014. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  72015. }
  72016. else {
  72017. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  72018. }
  72019. break;
  72020. case 1:
  72021. if (this._checkVerticesInsteadOfIndices) {
  72022. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  72023. }
  72024. else {
  72025. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  72026. }
  72027. break;
  72028. case 2:
  72029. if (this._checkVerticesInsteadOfIndices) {
  72030. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  72031. }
  72032. else {
  72033. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  72034. }
  72035. break;
  72036. }
  72037. if (otherEdgeIndex === -1) {
  72038. continue;
  72039. }
  72040. faceAdjacencies.edges[edgeIndex] = otherIndex;
  72041. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  72042. faceAdjacencies.edgesConnectedCount++;
  72043. otherFaceAdjacencies.edgesConnectedCount++;
  72044. if (faceAdjacencies.edgesConnectedCount === 3) {
  72045. break;
  72046. }
  72047. }
  72048. }
  72049. }
  72050. // Create lines
  72051. for (index = 0; index < adjacencies.length; index++) {
  72052. // 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
  72053. var current = adjacencies[index];
  72054. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  72055. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  72056. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  72057. }
  72058. // Merge into a single mesh
  72059. var engine = this._source.getScene().getEngine();
  72060. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  72061. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  72062. this._ib = engine.createIndexBuffer(this._linesIndices);
  72063. this._indicesCount = this._linesIndices.length;
  72064. };
  72065. EdgesRenderer.prototype.render = function () {
  72066. var scene = this._source.getScene();
  72067. if (!this._lineShader.isReady() || !scene.activeCamera) {
  72068. return;
  72069. }
  72070. var engine = scene.getEngine();
  72071. this._lineShader._preBind();
  72072. // VBOs
  72073. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  72074. scene.resetCachedMaterial();
  72075. this._lineShader.setColor4("color", this._source.edgesColor);
  72076. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  72077. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  72078. }
  72079. else {
  72080. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  72081. }
  72082. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  72083. this._lineShader.bind(this._source.getWorldMatrix());
  72084. // Draw order
  72085. engine.draw(true, 0, this._indicesCount);
  72086. this._lineShader.unbind();
  72087. engine.setDepthWrite(true);
  72088. };
  72089. return EdgesRenderer;
  72090. }());
  72091. BABYLON.EdgesRenderer = EdgesRenderer;
  72092. })(BABYLON || (BABYLON = {}));
  72093. //# sourceMappingURL=babylon.edgesRenderer.js.map
  72094. var BABYLON;
  72095. (function (BABYLON) {
  72096. /**
  72097. * Special Glow Blur post process only blurring the alpha channel
  72098. * It enforces keeping the most luminous color in the color channel.
  72099. */
  72100. var GlowBlurPostProcess = /** @class */ (function (_super) {
  72101. __extends(GlowBlurPostProcess, _super);
  72102. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  72103. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72104. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  72105. _this.direction = direction;
  72106. _this.kernel = kernel;
  72107. _this.onApplyObservable.add(function (effect) {
  72108. effect.setFloat2("screenSize", _this.width, _this.height);
  72109. effect.setVector2("direction", _this.direction);
  72110. effect.setFloat("blurWidth", _this.kernel);
  72111. });
  72112. return _this;
  72113. }
  72114. return GlowBlurPostProcess;
  72115. }(BABYLON.PostProcess));
  72116. /**
  72117. * The highlight layer Helps adding a glow effect around a mesh.
  72118. *
  72119. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  72120. * glowy meshes to your scene.
  72121. *
  72122. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  72123. */
  72124. var HighlightLayer = /** @class */ (function () {
  72125. /**
  72126. * Instantiates a new highlight Layer and references it to the scene..
  72127. * @param name The name of the layer
  72128. * @param scene The scene to use the layer in
  72129. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  72130. */
  72131. function HighlightLayer(name, scene, options) {
  72132. this.name = name;
  72133. this._vertexBuffers = {};
  72134. this._mainTextureDesiredSize = { width: 0, height: 0 };
  72135. this._meshes = {};
  72136. this._maxSize = 0;
  72137. this._shouldRender = false;
  72138. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  72139. this._excludedMeshes = {};
  72140. /**
  72141. * Specifies whether or not the inner glow is ACTIVE in the layer.
  72142. */
  72143. this.innerGlow = true;
  72144. /**
  72145. * Specifies whether or not the outer glow is ACTIVE in the layer.
  72146. */
  72147. this.outerGlow = true;
  72148. /**
  72149. * Specifies wether the highlight layer is enabled or not.
  72150. */
  72151. this.isEnabled = true;
  72152. /**
  72153. * An event triggered when the highlight layer has been disposed.
  72154. * @type {BABYLON.Observable}
  72155. */
  72156. this.onDisposeObservable = new BABYLON.Observable();
  72157. /**
  72158. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  72159. * @type {BABYLON.Observable}
  72160. */
  72161. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  72162. /**
  72163. * An event triggered when the highlight layer is being blurred.
  72164. * @type {BABYLON.Observable}
  72165. */
  72166. this.onBeforeBlurObservable = new BABYLON.Observable();
  72167. /**
  72168. * An event triggered when the highlight layer has been blurred.
  72169. * @type {BABYLON.Observable}
  72170. */
  72171. this.onAfterBlurObservable = new BABYLON.Observable();
  72172. /**
  72173. * An event triggered when the glowing blurred texture is being merged in the scene.
  72174. * @type {BABYLON.Observable}
  72175. */
  72176. this.onBeforeComposeObservable = new BABYLON.Observable();
  72177. /**
  72178. * An event triggered when the glowing blurred texture has been merged in the scene.
  72179. * @type {BABYLON.Observable}
  72180. */
  72181. this.onAfterComposeObservable = new BABYLON.Observable();
  72182. /**
  72183. * An event triggered when the highlight layer changes its size.
  72184. * @type {BABYLON.Observable}
  72185. */
  72186. this.onSizeChangedObservable = new BABYLON.Observable();
  72187. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  72188. var engine = scene.getEngine();
  72189. this._engine = engine;
  72190. this._maxSize = this._engine.getCaps().maxTextureSize;
  72191. this._scene.highlightLayers.push(this);
  72192. // Warn on stencil.
  72193. if (!this._engine.isStencilEnable) {
  72194. 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 }");
  72195. }
  72196. // Adapt options
  72197. this._options = options || {
  72198. mainTextureRatio: 0.5,
  72199. blurTextureSizeRatio: 0.5,
  72200. blurHorizontalSize: 1.0,
  72201. blurVerticalSize: 1.0,
  72202. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  72203. camera: null
  72204. };
  72205. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  72206. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  72207. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  72208. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  72209. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  72210. // VBO
  72211. var vertices = [];
  72212. vertices.push(1, 1);
  72213. vertices.push(-1, 1);
  72214. vertices.push(-1, -1);
  72215. vertices.push(1, -1);
  72216. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  72217. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  72218. this._createIndexBuffer();
  72219. // Effect
  72220. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  72221. // Render target
  72222. this.setMainTextureSize();
  72223. // Create Textures and post processes
  72224. this.createTextureAndPostProcesses();
  72225. }
  72226. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  72227. /**
  72228. * Gets the horizontal size of the blur.
  72229. */
  72230. get: function () {
  72231. return this._horizontalBlurPostprocess.kernel;
  72232. },
  72233. /**
  72234. * Specifies the horizontal size of the blur.
  72235. */
  72236. set: function (value) {
  72237. this._horizontalBlurPostprocess.kernel = value;
  72238. },
  72239. enumerable: true,
  72240. configurable: true
  72241. });
  72242. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  72243. /**
  72244. * Gets the vertical size of the blur.
  72245. */
  72246. get: function () {
  72247. return this._verticalBlurPostprocess.kernel;
  72248. },
  72249. /**
  72250. * Specifies the vertical size of the blur.
  72251. */
  72252. set: function (value) {
  72253. this._verticalBlurPostprocess.kernel = value;
  72254. },
  72255. enumerable: true,
  72256. configurable: true
  72257. });
  72258. Object.defineProperty(HighlightLayer.prototype, "camera", {
  72259. /**
  72260. * Gets the camera attached to the layer.
  72261. */
  72262. get: function () {
  72263. return this._options.camera;
  72264. },
  72265. enumerable: true,
  72266. configurable: true
  72267. });
  72268. HighlightLayer.prototype._createIndexBuffer = function () {
  72269. var engine = this._scene.getEngine();
  72270. // Indices
  72271. var indices = [];
  72272. indices.push(0);
  72273. indices.push(1);
  72274. indices.push(2);
  72275. indices.push(0);
  72276. indices.push(2);
  72277. indices.push(3);
  72278. this._indexBuffer = engine.createIndexBuffer(indices);
  72279. };
  72280. HighlightLayer.prototype._rebuild = function () {
  72281. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72282. if (vb) {
  72283. vb._rebuild();
  72284. }
  72285. this._createIndexBuffer();
  72286. };
  72287. /**
  72288. * Creates the render target textures and post processes used in the highlight layer.
  72289. */
  72290. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  72291. var _this = this;
  72292. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  72293. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  72294. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  72295. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  72296. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  72297. width: this._mainTextureDesiredSize.width,
  72298. height: this._mainTextureDesiredSize.height
  72299. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72300. this._mainTexture.activeCamera = this._options.camera;
  72301. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72302. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72303. this._mainTexture.anisotropicFilteringLevel = 1;
  72304. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72305. this._mainTexture.renderParticles = false;
  72306. this._mainTexture.renderList = null;
  72307. this._mainTexture.ignoreCameraViewport = true;
  72308. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  72309. width: blurTextureWidth,
  72310. height: blurTextureHeight
  72311. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72312. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72313. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72314. this._blurTexture.anisotropicFilteringLevel = 16;
  72315. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72316. this._blurTexture.renderParticles = false;
  72317. this._blurTexture.ignoreCameraViewport = true;
  72318. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72319. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  72320. effect.setTexture("textureSampler", _this._mainTexture);
  72321. });
  72322. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  72323. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72324. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72325. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72326. });
  72327. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72328. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72329. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72330. });
  72331. }
  72332. else {
  72333. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72334. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  72335. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72336. });
  72337. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  72338. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  72339. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  72340. });
  72341. }
  72342. this._mainTexture.onAfterUnbindObservable.add(function () {
  72343. _this.onBeforeBlurObservable.notifyObservers(_this);
  72344. var internalTexture = _this._blurTexture.getInternalTexture();
  72345. if (internalTexture) {
  72346. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  72347. }
  72348. _this.onAfterBlurObservable.notifyObservers(_this);
  72349. });
  72350. // Custom render function
  72351. var renderSubMesh = function (subMesh) {
  72352. if (!_this._meshes) {
  72353. return;
  72354. }
  72355. var material = subMesh.getMaterial();
  72356. var mesh = subMesh.getRenderingMesh();
  72357. var scene = _this._scene;
  72358. var engine = scene.getEngine();
  72359. if (!material) {
  72360. return;
  72361. }
  72362. // Culling
  72363. engine.setState(material.backFaceCulling);
  72364. // Managing instances
  72365. var batch = mesh._getInstancesRenderList(subMesh._id);
  72366. if (batch.mustReturn) {
  72367. return;
  72368. }
  72369. // Excluded Mesh
  72370. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72371. return;
  72372. }
  72373. ;
  72374. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  72375. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  72376. var emissiveTexture = null;
  72377. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  72378. emissiveTexture = material.emissiveTexture;
  72379. }
  72380. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  72381. engine.enableEffect(_this._glowMapGenerationEffect);
  72382. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  72383. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  72384. if (highlightLayerMesh) {
  72385. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  72386. }
  72387. else {
  72388. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  72389. }
  72390. // Alpha test
  72391. if (material && material.needAlphaTesting()) {
  72392. var alphaTexture = material.getAlphaTestTexture();
  72393. if (alphaTexture) {
  72394. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  72395. var textureMatrix = alphaTexture.getTextureMatrix();
  72396. if (textureMatrix) {
  72397. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  72398. }
  72399. }
  72400. }
  72401. // Glow emissive only
  72402. if (emissiveTexture) {
  72403. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  72404. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  72405. }
  72406. // Bones
  72407. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72408. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72409. }
  72410. // Draw
  72411. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  72412. }
  72413. else {
  72414. // Need to reset refresh rate of the shadowMap
  72415. _this._mainTexture.resetRefreshCounter();
  72416. }
  72417. };
  72418. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72419. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  72420. var index;
  72421. var engine = _this._scene.getEngine();
  72422. if (depthOnlySubMeshes.length) {
  72423. engine.setColorWrite(false);
  72424. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72425. renderSubMesh(depthOnlySubMeshes.data[index]);
  72426. }
  72427. engine.setColorWrite(true);
  72428. }
  72429. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72430. renderSubMesh(opaqueSubMeshes.data[index]);
  72431. }
  72432. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72433. renderSubMesh(alphaTestSubMeshes.data[index]);
  72434. }
  72435. for (index = 0; index < transparentSubMeshes.length; index++) {
  72436. renderSubMesh(transparentSubMeshes.data[index]);
  72437. }
  72438. };
  72439. this._mainTexture.onClearObservable.add(function (engine) {
  72440. engine.clear(HighlightLayer.neutralColor, true, true, true);
  72441. });
  72442. };
  72443. /**
  72444. * Checks for the readiness of the element composing the layer.
  72445. * @param subMesh the mesh to check for
  72446. * @param useInstances specify wether or not to use instances to render the mesh
  72447. * @param emissiveTexture the associated emissive texture used to generate the glow
  72448. * @return true if ready otherwise, false
  72449. */
  72450. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  72451. var material = subMesh.getMaterial();
  72452. if (!material) {
  72453. return false;
  72454. }
  72455. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  72456. return false;
  72457. }
  72458. var defines = [];
  72459. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72460. var mesh = subMesh.getMesh();
  72461. var uv1 = false;
  72462. var uv2 = false;
  72463. // Alpha test
  72464. if (material && material.needAlphaTesting()) {
  72465. var alphaTexture = material.getAlphaTestTexture();
  72466. if (alphaTexture) {
  72467. defines.push("#define ALPHATEST");
  72468. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72469. alphaTexture.coordinatesIndex === 1) {
  72470. defines.push("#define DIFFUSEUV2");
  72471. uv2 = true;
  72472. }
  72473. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72474. defines.push("#define DIFFUSEUV1");
  72475. uv1 = true;
  72476. }
  72477. }
  72478. }
  72479. // Emissive
  72480. if (emissiveTexture) {
  72481. defines.push("#define EMISSIVE");
  72482. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  72483. emissiveTexture.coordinatesIndex === 1) {
  72484. defines.push("#define EMISSIVEUV2");
  72485. uv2 = true;
  72486. }
  72487. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72488. defines.push("#define EMISSIVEUV1");
  72489. uv1 = true;
  72490. }
  72491. }
  72492. if (uv1) {
  72493. attribs.push(BABYLON.VertexBuffer.UVKind);
  72494. defines.push("#define UV1");
  72495. }
  72496. if (uv2) {
  72497. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72498. defines.push("#define UV2");
  72499. }
  72500. // Bones
  72501. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72502. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72503. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72504. if (mesh.numBoneInfluencers > 4) {
  72505. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72506. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72507. }
  72508. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72509. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  72510. }
  72511. else {
  72512. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72513. }
  72514. // Instances
  72515. if (useInstances) {
  72516. defines.push("#define INSTANCES");
  72517. attribs.push("world0");
  72518. attribs.push("world1");
  72519. attribs.push("world2");
  72520. attribs.push("world3");
  72521. }
  72522. // Get correct effect
  72523. var join = defines.join("\n");
  72524. if (this._cachedDefines !== join) {
  72525. this._cachedDefines = join;
  72526. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  72527. }
  72528. return this._glowMapGenerationEffect.isReady();
  72529. };
  72530. /**
  72531. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  72532. */
  72533. HighlightLayer.prototype.render = function () {
  72534. var currentEffect = this._glowMapMergeEffect;
  72535. // Check
  72536. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  72537. return;
  72538. var engine = this._scene.getEngine();
  72539. this.onBeforeComposeObservable.notifyObservers(this);
  72540. // Render
  72541. engine.enableEffect(currentEffect);
  72542. engine.setState(false);
  72543. // Cache
  72544. var previousStencilBuffer = engine.getStencilBuffer();
  72545. var previousStencilFunction = engine.getStencilFunction();
  72546. var previousStencilMask = engine.getStencilMask();
  72547. var previousStencilOperationPass = engine.getStencilOperationPass();
  72548. var previousStencilOperationFail = engine.getStencilOperationFail();
  72549. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  72550. var previousAlphaMode = engine.getAlphaMode();
  72551. // Texture
  72552. currentEffect.setTexture("textureSampler", this._blurTexture);
  72553. // VBOs
  72554. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  72555. // Stencil operations
  72556. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  72557. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  72558. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  72559. // Draw order
  72560. engine.setAlphaMode(this._options.alphaBlendingMode);
  72561. engine.setStencilMask(0x00);
  72562. engine.setStencilBuffer(true);
  72563. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  72564. if (this.outerGlow) {
  72565. currentEffect.setFloat("offset", 0);
  72566. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  72567. engine.draw(true, 0, 6);
  72568. }
  72569. if (this.innerGlow) {
  72570. currentEffect.setFloat("offset", 1);
  72571. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  72572. engine.draw(true, 0, 6);
  72573. }
  72574. // Restore Cache
  72575. engine.setStencilFunction(previousStencilFunction);
  72576. engine.setStencilMask(previousStencilMask);
  72577. engine.setAlphaMode(previousAlphaMode);
  72578. engine.setStencilBuffer(previousStencilBuffer);
  72579. engine.setStencilOperationPass(previousStencilOperationPass);
  72580. engine.setStencilOperationFail(previousStencilOperationFail);
  72581. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  72582. engine._stencilState.reset();
  72583. this.onAfterComposeObservable.notifyObservers(this);
  72584. // Handle size changes.
  72585. var size = this._mainTexture.getSize();
  72586. this.setMainTextureSize();
  72587. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  72588. // Recreate RTT and post processes on size change.
  72589. this.onSizeChangedObservable.notifyObservers(this);
  72590. this.disposeTextureAndPostProcesses();
  72591. this.createTextureAndPostProcesses();
  72592. }
  72593. };
  72594. /**
  72595. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  72596. * @param mesh The mesh to exclude from the highlight layer
  72597. */
  72598. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  72599. if (!this._excludedMeshes) {
  72600. return;
  72601. }
  72602. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72603. if (!meshExcluded) {
  72604. this._excludedMeshes[mesh.uniqueId] = {
  72605. mesh: mesh,
  72606. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  72607. mesh.getEngine().setStencilBuffer(false);
  72608. }),
  72609. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  72610. mesh.getEngine().setStencilBuffer(true);
  72611. }),
  72612. };
  72613. }
  72614. };
  72615. /**
  72616. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  72617. * @param mesh The mesh to highlight
  72618. */
  72619. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  72620. if (!this._excludedMeshes) {
  72621. return;
  72622. }
  72623. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  72624. if (meshExcluded) {
  72625. if (meshExcluded.beforeRender) {
  72626. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  72627. }
  72628. if (meshExcluded.afterRender) {
  72629. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  72630. }
  72631. }
  72632. this._excludedMeshes[mesh.uniqueId] = null;
  72633. };
  72634. /**
  72635. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  72636. * @param mesh The mesh to highlight
  72637. * @param color The color of the highlight
  72638. * @param glowEmissiveOnly Extract the glow from the emissive texture
  72639. */
  72640. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  72641. var _this = this;
  72642. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  72643. if (!this._meshes) {
  72644. return;
  72645. }
  72646. var meshHighlight = this._meshes[mesh.uniqueId];
  72647. if (meshHighlight) {
  72648. meshHighlight.color = color;
  72649. }
  72650. else {
  72651. this._meshes[mesh.uniqueId] = {
  72652. mesh: mesh,
  72653. color: color,
  72654. // Lambda required for capture due to Observable this context
  72655. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  72656. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  72657. _this.defaultStencilReference(mesh);
  72658. }
  72659. else {
  72660. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  72661. }
  72662. }),
  72663. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  72664. glowEmissiveOnly: glowEmissiveOnly
  72665. };
  72666. }
  72667. this._shouldRender = true;
  72668. };
  72669. /**
  72670. * Remove a mesh from the highlight layer in order to make it stop glowing.
  72671. * @param mesh The mesh to highlight
  72672. */
  72673. HighlightLayer.prototype.removeMesh = function (mesh) {
  72674. if (!this._meshes) {
  72675. return;
  72676. }
  72677. var meshHighlight = this._meshes[mesh.uniqueId];
  72678. if (meshHighlight) {
  72679. if (meshHighlight.observerHighlight) {
  72680. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72681. }
  72682. if (meshHighlight.observerDefault) {
  72683. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72684. }
  72685. }
  72686. this._meshes[mesh.uniqueId] = null;
  72687. this._shouldRender = false;
  72688. for (var meshHighlightToCheck in this._meshes) {
  72689. if (meshHighlightToCheck) {
  72690. this._shouldRender = true;
  72691. break;
  72692. }
  72693. }
  72694. };
  72695. /**
  72696. * Returns true if the layer contains information to display, otherwise false.
  72697. */
  72698. HighlightLayer.prototype.shouldRender = function () {
  72699. return this.isEnabled && this._shouldRender;
  72700. };
  72701. /**
  72702. * Sets the main texture desired size which is the closest power of two
  72703. * of the engine canvas size.
  72704. */
  72705. HighlightLayer.prototype.setMainTextureSize = function () {
  72706. if (this._options.mainTextureFixedSize) {
  72707. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  72708. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  72709. }
  72710. else {
  72711. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  72712. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  72713. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  72714. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  72715. }
  72716. };
  72717. /**
  72718. * Force the stencil to the normal expected value for none glowing parts
  72719. */
  72720. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  72721. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  72722. };
  72723. /**
  72724. * Dispose only the render target textures and post process.
  72725. */
  72726. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  72727. this._blurTexture.dispose();
  72728. this._mainTexture.dispose();
  72729. this._downSamplePostprocess.dispose();
  72730. this._horizontalBlurPostprocess.dispose();
  72731. this._verticalBlurPostprocess.dispose();
  72732. };
  72733. /**
  72734. * Dispose the highlight layer and free resources.
  72735. */
  72736. HighlightLayer.prototype.dispose = function () {
  72737. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  72738. if (vertexBuffer) {
  72739. vertexBuffer.dispose();
  72740. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  72741. }
  72742. if (this._indexBuffer) {
  72743. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  72744. this._indexBuffer = null;
  72745. }
  72746. // Clean textures and post processes
  72747. this.disposeTextureAndPostProcesses();
  72748. if (this._meshes) {
  72749. // Clean mesh references
  72750. for (var id in this._meshes) {
  72751. var meshHighlight = this._meshes[id];
  72752. if (meshHighlight && meshHighlight.mesh) {
  72753. if (meshHighlight.observerHighlight) {
  72754. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  72755. }
  72756. if (meshHighlight.observerDefault) {
  72757. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  72758. }
  72759. }
  72760. }
  72761. this._meshes = null;
  72762. }
  72763. if (this._excludedMeshes) {
  72764. for (var id in this._excludedMeshes) {
  72765. var meshHighlight = this._excludedMeshes[id];
  72766. if (meshHighlight) {
  72767. if (meshHighlight.beforeRender) {
  72768. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  72769. }
  72770. if (meshHighlight.afterRender) {
  72771. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  72772. }
  72773. }
  72774. }
  72775. this._excludedMeshes = null;
  72776. }
  72777. // Remove from scene
  72778. var index = this._scene.highlightLayers.indexOf(this, 0);
  72779. if (index > -1) {
  72780. this._scene.highlightLayers.splice(index, 1);
  72781. }
  72782. // Callback
  72783. this.onDisposeObservable.notifyObservers(this);
  72784. this.onDisposeObservable.clear();
  72785. this.onBeforeRenderMainTextureObservable.clear();
  72786. this.onBeforeBlurObservable.clear();
  72787. this.onBeforeComposeObservable.clear();
  72788. this.onAfterComposeObservable.clear();
  72789. this.onSizeChangedObservable.clear();
  72790. };
  72791. /**
  72792. * The neutral color used during the preparation of the glow effect.
  72793. * This is black by default as the blend operation is a blend operation.
  72794. */
  72795. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  72796. /**
  72797. * Stencil value used for glowing meshes.
  72798. */
  72799. HighlightLayer.glowingMeshStencilReference = 0x02;
  72800. /**
  72801. * Stencil value used for the other meshes in the scene.
  72802. */
  72803. HighlightLayer.normalMeshStencilReference = 0x01;
  72804. return HighlightLayer;
  72805. }());
  72806. BABYLON.HighlightLayer = HighlightLayer;
  72807. })(BABYLON || (BABYLON = {}));
  72808. //# sourceMappingURL=babylon.highlightlayer.js.map
  72809. var BABYLON;
  72810. (function (BABYLON) {
  72811. var AssetTaskState;
  72812. (function (AssetTaskState) {
  72813. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  72814. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  72815. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  72816. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  72817. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  72818. var AbstractAssetTask = /** @class */ (function () {
  72819. function AbstractAssetTask(name) {
  72820. this.name = name;
  72821. this.isCompleted = false;
  72822. this.taskState = AssetTaskState.INIT;
  72823. }
  72824. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  72825. var _this = this;
  72826. this.taskState = AssetTaskState.RUNNING;
  72827. this.runTask(scene, function () {
  72828. _this.onDoneCallback(onSuccess, onError);
  72829. }, function (msg, exception) {
  72830. _this.onErrorCallback(onError, msg, exception);
  72831. });
  72832. };
  72833. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72834. throw new Error("runTask is not implemented");
  72835. };
  72836. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  72837. this.taskState = AssetTaskState.ERROR;
  72838. this.errorObject = {
  72839. message: message,
  72840. exception: exception
  72841. };
  72842. if (this.onError) {
  72843. this.onError(this, message, exception);
  72844. }
  72845. onError();
  72846. };
  72847. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  72848. try {
  72849. this.taskState = AssetTaskState.DONE;
  72850. this.isCompleted = true;
  72851. if (this.onSuccess) {
  72852. this.onSuccess(this);
  72853. }
  72854. onSuccess();
  72855. }
  72856. catch (e) {
  72857. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  72858. }
  72859. };
  72860. return AbstractAssetTask;
  72861. }());
  72862. BABYLON.AbstractAssetTask = AbstractAssetTask;
  72863. var AssetsProgressEvent = /** @class */ (function () {
  72864. function AssetsProgressEvent(remainingCount, totalCount, task) {
  72865. this.remainingCount = remainingCount;
  72866. this.totalCount = totalCount;
  72867. this.task = task;
  72868. }
  72869. return AssetsProgressEvent;
  72870. }());
  72871. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  72872. var MeshAssetTask = /** @class */ (function (_super) {
  72873. __extends(MeshAssetTask, _super);
  72874. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  72875. var _this = _super.call(this, name) || this;
  72876. _this.name = name;
  72877. _this.meshesNames = meshesNames;
  72878. _this.rootUrl = rootUrl;
  72879. _this.sceneFilename = sceneFilename;
  72880. return _this;
  72881. }
  72882. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72883. var _this = this;
  72884. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  72885. _this.loadedMeshes = meshes;
  72886. _this.loadedParticleSystems = particleSystems;
  72887. _this.loadedSkeletons = skeletons;
  72888. onSuccess();
  72889. }, null, function (scene, message, exception) {
  72890. onError(message, exception);
  72891. });
  72892. };
  72893. return MeshAssetTask;
  72894. }(AbstractAssetTask));
  72895. BABYLON.MeshAssetTask = MeshAssetTask;
  72896. var TextFileAssetTask = /** @class */ (function (_super) {
  72897. __extends(TextFileAssetTask, _super);
  72898. function TextFileAssetTask(name, url) {
  72899. var _this = _super.call(this, name) || this;
  72900. _this.name = name;
  72901. _this.url = url;
  72902. return _this;
  72903. }
  72904. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72905. var _this = this;
  72906. BABYLON.Tools.LoadFile(this.url, function (data) {
  72907. _this.text = data;
  72908. onSuccess();
  72909. }, undefined, scene.database, false, function (request, exception) {
  72910. if (request) {
  72911. onError(request.status + " " + request.statusText, exception);
  72912. }
  72913. });
  72914. };
  72915. return TextFileAssetTask;
  72916. }(AbstractAssetTask));
  72917. BABYLON.TextFileAssetTask = TextFileAssetTask;
  72918. var BinaryFileAssetTask = /** @class */ (function (_super) {
  72919. __extends(BinaryFileAssetTask, _super);
  72920. function BinaryFileAssetTask(name, url) {
  72921. var _this = _super.call(this, name) || this;
  72922. _this.name = name;
  72923. _this.url = url;
  72924. return _this;
  72925. }
  72926. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72927. var _this = this;
  72928. BABYLON.Tools.LoadFile(this.url, function (data) {
  72929. _this.data = data;
  72930. onSuccess();
  72931. }, undefined, scene.database, true, function (request, exception) {
  72932. if (request) {
  72933. onError(request.status + " " + request.statusText, exception);
  72934. }
  72935. });
  72936. };
  72937. return BinaryFileAssetTask;
  72938. }(AbstractAssetTask));
  72939. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  72940. var ImageAssetTask = /** @class */ (function (_super) {
  72941. __extends(ImageAssetTask, _super);
  72942. function ImageAssetTask(name, url) {
  72943. var _this = _super.call(this, name) || this;
  72944. _this.name = name;
  72945. _this.url = url;
  72946. return _this;
  72947. }
  72948. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72949. var _this = this;
  72950. var img = new Image();
  72951. BABYLON.Tools.SetCorsBehavior(this.url, img);
  72952. img.onload = function () {
  72953. _this.image = img;
  72954. onSuccess();
  72955. };
  72956. img.onerror = function (err) {
  72957. onError("Error loading image", err);
  72958. };
  72959. img.src = this.url;
  72960. };
  72961. return ImageAssetTask;
  72962. }(AbstractAssetTask));
  72963. BABYLON.ImageAssetTask = ImageAssetTask;
  72964. var TextureAssetTask = /** @class */ (function (_super) {
  72965. __extends(TextureAssetTask, _super);
  72966. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  72967. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72968. var _this = _super.call(this, name) || this;
  72969. _this.name = name;
  72970. _this.url = url;
  72971. _this.noMipmap = noMipmap;
  72972. _this.invertY = invertY;
  72973. _this.samplingMode = samplingMode;
  72974. return _this;
  72975. }
  72976. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  72977. var onload = function () {
  72978. onSuccess();
  72979. };
  72980. var onerror = function (msg, exception) {
  72981. onError(msg, exception);
  72982. };
  72983. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  72984. };
  72985. return TextureAssetTask;
  72986. }(AbstractAssetTask));
  72987. BABYLON.TextureAssetTask = TextureAssetTask;
  72988. var CubeTextureAssetTask = /** @class */ (function (_super) {
  72989. __extends(CubeTextureAssetTask, _super);
  72990. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  72991. var _this = _super.call(this, name) || this;
  72992. _this.name = name;
  72993. _this.url = url;
  72994. _this.extensions = extensions;
  72995. _this.noMipmap = noMipmap;
  72996. _this.files = files;
  72997. return _this;
  72998. }
  72999. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  73000. var onload = function () {
  73001. onSuccess();
  73002. };
  73003. var onerror = function (msg, exception) {
  73004. onError(msg, exception);
  73005. };
  73006. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  73007. };
  73008. return CubeTextureAssetTask;
  73009. }(AbstractAssetTask));
  73010. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  73011. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  73012. __extends(HDRCubeTextureAssetTask, _super);
  73013. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  73014. if (noMipmap === void 0) { noMipmap = false; }
  73015. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73016. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73017. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73018. var _this = _super.call(this, name) || this;
  73019. _this.name = name;
  73020. _this.url = url;
  73021. _this.size = size;
  73022. _this.noMipmap = noMipmap;
  73023. _this.generateHarmonics = generateHarmonics;
  73024. _this.useInGammaSpace = useInGammaSpace;
  73025. _this.usePMREMGenerator = usePMREMGenerator;
  73026. return _this;
  73027. }
  73028. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  73029. var onload = function () {
  73030. onSuccess();
  73031. };
  73032. var onerror = function (message, exception) {
  73033. onError(message, exception);
  73034. };
  73035. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  73036. };
  73037. return HDRCubeTextureAssetTask;
  73038. }(AbstractAssetTask));
  73039. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  73040. var AssetsManager = /** @class */ (function () {
  73041. function AssetsManager(scene) {
  73042. this.tasks = new Array();
  73043. this.waitingTasksCount = 0;
  73044. //Observables
  73045. this.onTaskSuccessObservable = new BABYLON.Observable();
  73046. this.onTaskErrorObservable = new BABYLON.Observable();
  73047. this.onTasksDoneObservable = new BABYLON.Observable();
  73048. this.onProgressObservable = new BABYLON.Observable();
  73049. this.useDefaultLoadingScreen = true;
  73050. this._scene = scene;
  73051. }
  73052. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  73053. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  73054. this.tasks.push(task);
  73055. return task;
  73056. };
  73057. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  73058. var task = new TextFileAssetTask(taskName, url);
  73059. this.tasks.push(task);
  73060. return task;
  73061. };
  73062. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  73063. var task = new BinaryFileAssetTask(taskName, url);
  73064. this.tasks.push(task);
  73065. return task;
  73066. };
  73067. AssetsManager.prototype.addImageTask = function (taskName, url) {
  73068. var task = new ImageAssetTask(taskName, url);
  73069. this.tasks.push(task);
  73070. return task;
  73071. };
  73072. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  73073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73074. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  73075. this.tasks.push(task);
  73076. return task;
  73077. };
  73078. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  73079. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  73080. this.tasks.push(task);
  73081. return task;
  73082. };
  73083. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  73084. if (noMipmap === void 0) { noMipmap = false; }
  73085. if (generateHarmonics === void 0) { generateHarmonics = true; }
  73086. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  73087. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  73088. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  73089. this.tasks.push(task);
  73090. return task;
  73091. };
  73092. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  73093. this.waitingTasksCount--;
  73094. try {
  73095. if (this.onProgress) {
  73096. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  73097. }
  73098. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  73099. }
  73100. catch (e) {
  73101. BABYLON.Tools.Error("Error running progress callbacks.");
  73102. console.log(e);
  73103. }
  73104. if (this.waitingTasksCount === 0) {
  73105. try {
  73106. if (this.onFinish) {
  73107. this.onFinish(this.tasks);
  73108. }
  73109. this.onTasksDoneObservable.notifyObservers(this.tasks);
  73110. }
  73111. catch (e) {
  73112. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  73113. console.log(e);
  73114. }
  73115. this._scene.getEngine().hideLoadingUI();
  73116. }
  73117. };
  73118. AssetsManager.prototype._runTask = function (task) {
  73119. var _this = this;
  73120. var done = function () {
  73121. try {
  73122. if (_this.onTaskSuccess) {
  73123. _this.onTaskSuccess(task);
  73124. }
  73125. _this.onTaskSuccessObservable.notifyObservers(task);
  73126. _this._decreaseWaitingTasksCount(task);
  73127. }
  73128. catch (e) {
  73129. error("Error executing task success callbacks", e);
  73130. }
  73131. };
  73132. var error = function (message, exception) {
  73133. task.errorObject = task.errorObject || {
  73134. message: message,
  73135. exception: exception
  73136. };
  73137. if (_this.onTaskError) {
  73138. _this.onTaskError(task);
  73139. }
  73140. _this.onTaskErrorObservable.notifyObservers(task);
  73141. _this._decreaseWaitingTasksCount(task);
  73142. };
  73143. task.run(this._scene, done, error);
  73144. };
  73145. AssetsManager.prototype.reset = function () {
  73146. this.tasks = new Array();
  73147. return this;
  73148. };
  73149. AssetsManager.prototype.load = function () {
  73150. this.waitingTasksCount = this.tasks.length;
  73151. if (this.waitingTasksCount === 0) {
  73152. if (this.onFinish) {
  73153. this.onFinish(this.tasks);
  73154. }
  73155. this.onTasksDoneObservable.notifyObservers(this.tasks);
  73156. return this;
  73157. }
  73158. if (this.useDefaultLoadingScreen) {
  73159. this._scene.getEngine().displayLoadingUI();
  73160. }
  73161. for (var index = 0; index < this.tasks.length; index++) {
  73162. var task = this.tasks[index];
  73163. this._runTask(task);
  73164. }
  73165. return this;
  73166. };
  73167. return AssetsManager;
  73168. }());
  73169. BABYLON.AssetsManager = AssetsManager;
  73170. })(BABYLON || (BABYLON = {}));
  73171. //# sourceMappingURL=babylon.assetsManager.js.map
  73172. var BABYLON;
  73173. (function (BABYLON) {
  73174. var serializedGeometries = [];
  73175. var serializeGeometry = function (geometry, serializationGeometries) {
  73176. if (serializedGeometries[geometry.id]) {
  73177. return;
  73178. }
  73179. if (geometry.doNotSerialize) {
  73180. return;
  73181. }
  73182. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  73183. serializationGeometries.boxes.push(geometry.serialize());
  73184. }
  73185. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  73186. serializationGeometries.spheres.push(geometry.serialize());
  73187. }
  73188. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  73189. serializationGeometries.cylinders.push(geometry.serialize());
  73190. }
  73191. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  73192. serializationGeometries.toruses.push(geometry.serialize());
  73193. }
  73194. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  73195. serializationGeometries.grounds.push(geometry.serialize());
  73196. }
  73197. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  73198. serializationGeometries.planes.push(geometry.serialize());
  73199. }
  73200. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  73201. serializationGeometries.torusKnots.push(geometry.serialize());
  73202. }
  73203. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  73204. throw new Error("Unknown primitive type");
  73205. }
  73206. else {
  73207. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  73208. }
  73209. serializedGeometries[geometry.id] = true;
  73210. };
  73211. var serializeMesh = function (mesh, serializationScene) {
  73212. var serializationObject = {};
  73213. // Geometry
  73214. var geometry = mesh._geometry;
  73215. if (geometry) {
  73216. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  73217. // 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
  73218. serializeGeometry(geometry, serializationScene.geometries);
  73219. }
  73220. }
  73221. // Custom
  73222. if (mesh.serialize) {
  73223. mesh.serialize(serializationObject);
  73224. }
  73225. return serializationObject;
  73226. };
  73227. var finalizeSingleMesh = function (mesh, serializationObject) {
  73228. //only works if the mesh is already loaded
  73229. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73230. //serialize material
  73231. if (mesh.material) {
  73232. if (mesh.material instanceof BABYLON.StandardMaterial) {
  73233. serializationObject.materials = serializationObject.materials || [];
  73234. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  73235. serializationObject.materials.push(mesh.material.serialize());
  73236. }
  73237. }
  73238. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  73239. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  73240. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  73241. serializationObject.multiMaterials.push(mesh.material.serialize());
  73242. }
  73243. }
  73244. }
  73245. //serialize geometry
  73246. var geometry = mesh._geometry;
  73247. if (geometry) {
  73248. if (!serializationObject.geometries) {
  73249. serializationObject.geometries = {};
  73250. serializationObject.geometries.boxes = [];
  73251. serializationObject.geometries.spheres = [];
  73252. serializationObject.geometries.cylinders = [];
  73253. serializationObject.geometries.toruses = [];
  73254. serializationObject.geometries.grounds = [];
  73255. serializationObject.geometries.planes = [];
  73256. serializationObject.geometries.torusKnots = [];
  73257. serializationObject.geometries.vertexData = [];
  73258. }
  73259. serializeGeometry(geometry, serializationObject.geometries);
  73260. }
  73261. // Skeletons
  73262. if (mesh.skeleton) {
  73263. serializationObject.skeletons = serializationObject.skeletons || [];
  73264. serializationObject.skeletons.push(mesh.skeleton.serialize());
  73265. }
  73266. //serialize the actual mesh
  73267. serializationObject.meshes = serializationObject.meshes || [];
  73268. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73269. }
  73270. };
  73271. var SceneSerializer = /** @class */ (function () {
  73272. function SceneSerializer() {
  73273. }
  73274. SceneSerializer.ClearCache = function () {
  73275. serializedGeometries = [];
  73276. };
  73277. SceneSerializer.Serialize = function (scene) {
  73278. var serializationObject = {};
  73279. SceneSerializer.ClearCache();
  73280. // Scene
  73281. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  73282. serializationObject.autoClear = scene.autoClear;
  73283. serializationObject.clearColor = scene.clearColor.asArray();
  73284. serializationObject.ambientColor = scene.ambientColor.asArray();
  73285. serializationObject.gravity = scene.gravity.asArray();
  73286. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  73287. serializationObject.workerCollisions = scene.workerCollisions;
  73288. // Fog
  73289. if (scene.fogMode && scene.fogMode !== 0) {
  73290. serializationObject.fogMode = scene.fogMode;
  73291. serializationObject.fogColor = scene.fogColor.asArray();
  73292. serializationObject.fogStart = scene.fogStart;
  73293. serializationObject.fogEnd = scene.fogEnd;
  73294. serializationObject.fogDensity = scene.fogDensity;
  73295. }
  73296. //Physics
  73297. if (scene.isPhysicsEnabled()) {
  73298. var physicEngine = scene.getPhysicsEngine();
  73299. if (physicEngine) {
  73300. serializationObject.physicsEnabled = true;
  73301. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  73302. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  73303. }
  73304. }
  73305. // Metadata
  73306. if (scene.metadata) {
  73307. serializationObject.metadata = scene.metadata;
  73308. }
  73309. // Morph targets
  73310. serializationObject.morphTargetManagers = [];
  73311. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  73312. var abstractMesh = _a[_i];
  73313. var manager = abstractMesh.morphTargetManager;
  73314. if (manager) {
  73315. serializationObject.morphTargetManagers.push(manager.serialize());
  73316. }
  73317. }
  73318. // Lights
  73319. serializationObject.lights = [];
  73320. var index;
  73321. var light;
  73322. for (index = 0; index < scene.lights.length; index++) {
  73323. light = scene.lights[index];
  73324. if (!light.doNotSerialize) {
  73325. serializationObject.lights.push(light.serialize());
  73326. }
  73327. }
  73328. // Cameras
  73329. serializationObject.cameras = [];
  73330. for (index = 0; index < scene.cameras.length; index++) {
  73331. var camera = scene.cameras[index];
  73332. if (!camera.doNotSerialize) {
  73333. serializationObject.cameras.push(camera.serialize());
  73334. }
  73335. }
  73336. if (scene.activeCamera) {
  73337. serializationObject.activeCameraID = scene.activeCamera.id;
  73338. }
  73339. // Animations
  73340. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  73341. // Materials
  73342. serializationObject.materials = [];
  73343. serializationObject.multiMaterials = [];
  73344. var material;
  73345. for (index = 0; index < scene.materials.length; index++) {
  73346. material = scene.materials[index];
  73347. if (!material.doNotSerialize) {
  73348. serializationObject.materials.push(material.serialize());
  73349. }
  73350. }
  73351. // MultiMaterials
  73352. serializationObject.multiMaterials = [];
  73353. for (index = 0; index < scene.multiMaterials.length; index++) {
  73354. var multiMaterial = scene.multiMaterials[index];
  73355. serializationObject.multiMaterials.push(multiMaterial.serialize());
  73356. }
  73357. // Skeletons
  73358. serializationObject.skeletons = [];
  73359. for (index = 0; index < scene.skeletons.length; index++) {
  73360. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  73361. }
  73362. // Geometries
  73363. serializationObject.geometries = {};
  73364. serializationObject.geometries.boxes = [];
  73365. serializationObject.geometries.spheres = [];
  73366. serializationObject.geometries.cylinders = [];
  73367. serializationObject.geometries.toruses = [];
  73368. serializationObject.geometries.grounds = [];
  73369. serializationObject.geometries.planes = [];
  73370. serializationObject.geometries.torusKnots = [];
  73371. serializationObject.geometries.vertexData = [];
  73372. serializedGeometries = [];
  73373. var geometries = scene.getGeometries();
  73374. for (index = 0; index < geometries.length; index++) {
  73375. var geometry = geometries[index];
  73376. if (geometry.isReady()) {
  73377. serializeGeometry(geometry, serializationObject.geometries);
  73378. }
  73379. }
  73380. // Meshes
  73381. serializationObject.meshes = [];
  73382. for (index = 0; index < scene.meshes.length; index++) {
  73383. var abstractMesh = scene.meshes[index];
  73384. if (abstractMesh instanceof BABYLON.Mesh) {
  73385. var mesh = abstractMesh;
  73386. if (!mesh.doNotSerialize) {
  73387. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  73388. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  73389. }
  73390. }
  73391. }
  73392. }
  73393. // Particles Systems
  73394. serializationObject.particleSystems = [];
  73395. for (index = 0; index < scene.particleSystems.length; index++) {
  73396. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  73397. }
  73398. // Lens flares
  73399. serializationObject.lensFlareSystems = [];
  73400. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  73401. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  73402. }
  73403. // Shadows
  73404. serializationObject.shadowGenerators = [];
  73405. for (index = 0; index < scene.lights.length; index++) {
  73406. light = scene.lights[index];
  73407. var shadowGenerator = light.getShadowGenerator();
  73408. if (shadowGenerator) {
  73409. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  73410. }
  73411. }
  73412. // Action Manager
  73413. if (scene.actionManager) {
  73414. serializationObject.actions = scene.actionManager.serialize("scene");
  73415. }
  73416. // Audio
  73417. serializationObject.sounds = [];
  73418. for (index = 0; index < scene.soundTracks.length; index++) {
  73419. var soundtrack = scene.soundTracks[index];
  73420. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  73421. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  73422. }
  73423. }
  73424. return serializationObject;
  73425. };
  73426. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  73427. if (withParents === void 0) { withParents = false; }
  73428. if (withChildren === void 0) { withChildren = false; }
  73429. var serializationObject = {};
  73430. SceneSerializer.ClearCache();
  73431. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  73432. if (withParents || withChildren) {
  73433. //deliberate for loop! not for each, appended should be processed as well.
  73434. for (var i = 0; i < toSerialize.length; ++i) {
  73435. if (withChildren) {
  73436. toSerialize[i].getDescendants().forEach(function (node) {
  73437. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  73438. toSerialize.push(node);
  73439. }
  73440. });
  73441. }
  73442. //make sure the array doesn't contain the object already
  73443. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  73444. toSerialize.push(toSerialize[i].parent);
  73445. }
  73446. }
  73447. }
  73448. toSerialize.forEach(function (mesh) {
  73449. finalizeSingleMesh(mesh, serializationObject);
  73450. });
  73451. return serializationObject;
  73452. };
  73453. return SceneSerializer;
  73454. }());
  73455. BABYLON.SceneSerializer = SceneSerializer;
  73456. })(BABYLON || (BABYLON = {}));
  73457. //# sourceMappingURL=babylon.sceneSerializer.js.map
  73458. var BABYLON;
  73459. (function (BABYLON) {
  73460. var ReflectionProbe = /** @class */ (function () {
  73461. function ReflectionProbe(name, size, scene, generateMipMaps) {
  73462. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73463. var _this = this;
  73464. this.name = name;
  73465. this._viewMatrix = BABYLON.Matrix.Identity();
  73466. this._target = BABYLON.Vector3.Zero();
  73467. this._add = BABYLON.Vector3.Zero();
  73468. this.invertYAxis = false;
  73469. this.position = BABYLON.Vector3.Zero();
  73470. this._scene = scene;
  73471. this._scene.reflectionProbes.push(this);
  73472. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  73473. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  73474. switch (faceIndex) {
  73475. case 0:
  73476. _this._add.copyFromFloats(1, 0, 0);
  73477. break;
  73478. case 1:
  73479. _this._add.copyFromFloats(-1, 0, 0);
  73480. break;
  73481. case 2:
  73482. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  73483. break;
  73484. case 3:
  73485. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  73486. break;
  73487. case 4:
  73488. _this._add.copyFromFloats(0, 0, 1);
  73489. break;
  73490. case 5:
  73491. _this._add.copyFromFloats(0, 0, -1);
  73492. break;
  73493. }
  73494. if (_this._attachedMesh) {
  73495. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  73496. }
  73497. _this.position.addToRef(_this._add, _this._target);
  73498. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  73499. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  73500. scene._forcedViewPosition = _this.position;
  73501. });
  73502. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  73503. scene._forcedViewPosition = null;
  73504. scene.updateTransformMatrix(true);
  73505. });
  73506. if (scene.activeCamera) {
  73507. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  73508. }
  73509. }
  73510. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  73511. get: function () {
  73512. return this._renderTargetTexture.samples;
  73513. },
  73514. set: function (value) {
  73515. this._renderTargetTexture.samples = value;
  73516. },
  73517. enumerable: true,
  73518. configurable: true
  73519. });
  73520. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  73521. get: function () {
  73522. return this._renderTargetTexture.refreshRate;
  73523. },
  73524. set: function (value) {
  73525. this._renderTargetTexture.refreshRate = value;
  73526. },
  73527. enumerable: true,
  73528. configurable: true
  73529. });
  73530. ReflectionProbe.prototype.getScene = function () {
  73531. return this._scene;
  73532. };
  73533. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  73534. get: function () {
  73535. return this._renderTargetTexture;
  73536. },
  73537. enumerable: true,
  73538. configurable: true
  73539. });
  73540. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  73541. get: function () {
  73542. return this._renderTargetTexture.renderList;
  73543. },
  73544. enumerable: true,
  73545. configurable: true
  73546. });
  73547. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  73548. this._attachedMesh = mesh;
  73549. };
  73550. /**
  73551. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  73552. *
  73553. * @param renderingGroupId The rendering group id corresponding to its index
  73554. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  73555. */
  73556. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  73557. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  73558. };
  73559. ReflectionProbe.prototype.dispose = function () {
  73560. var index = this._scene.reflectionProbes.indexOf(this);
  73561. if (index !== -1) {
  73562. // Remove from the scene if found
  73563. this._scene.reflectionProbes.splice(index, 1);
  73564. }
  73565. if (this._renderTargetTexture) {
  73566. this._renderTargetTexture.dispose();
  73567. this._renderTargetTexture = null;
  73568. }
  73569. };
  73570. return ReflectionProbe;
  73571. }());
  73572. BABYLON.ReflectionProbe = ReflectionProbe;
  73573. })(BABYLON || (BABYLON = {}));
  73574. //# sourceMappingURL=babylon.reflectionProbe.js.map
  73575. var BABYLON;
  73576. (function (BABYLON) {
  73577. var Layer = /** @class */ (function () {
  73578. function Layer(name, imgUrl, scene, isBackground, color) {
  73579. this.name = name;
  73580. this.scale = new BABYLON.Vector2(1, 1);
  73581. this.offset = new BABYLON.Vector2(0, 0);
  73582. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  73583. this.layerMask = 0x0FFFFFFF;
  73584. this._vertexBuffers = {};
  73585. // Events
  73586. /**
  73587. * An event triggered when the layer is disposed.
  73588. * @type {BABYLON.Observable}
  73589. */
  73590. this.onDisposeObservable = new BABYLON.Observable();
  73591. /**
  73592. * An event triggered before rendering the scene
  73593. * @type {BABYLON.Observable}
  73594. */
  73595. this.onBeforeRenderObservable = new BABYLON.Observable();
  73596. /**
  73597. * An event triggered after rendering the scene
  73598. * @type {BABYLON.Observable}
  73599. */
  73600. this.onAfterRenderObservable = new BABYLON.Observable();
  73601. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  73602. this.isBackground = isBackground === undefined ? true : isBackground;
  73603. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  73604. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  73605. this._scene.layers.push(this);
  73606. var engine = this._scene.getEngine();
  73607. // VBO
  73608. var vertices = [];
  73609. vertices.push(1, 1);
  73610. vertices.push(-1, 1);
  73611. vertices.push(-1, -1);
  73612. vertices.push(1, -1);
  73613. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73614. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  73615. this._createIndexBuffer();
  73616. // Effects
  73617. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  73618. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  73619. }
  73620. Object.defineProperty(Layer.prototype, "onDispose", {
  73621. set: function (callback) {
  73622. if (this._onDisposeObserver) {
  73623. this.onDisposeObservable.remove(this._onDisposeObserver);
  73624. }
  73625. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  73626. },
  73627. enumerable: true,
  73628. configurable: true
  73629. });
  73630. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  73631. set: function (callback) {
  73632. if (this._onBeforeRenderObserver) {
  73633. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  73634. }
  73635. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  73636. },
  73637. enumerable: true,
  73638. configurable: true
  73639. });
  73640. Object.defineProperty(Layer.prototype, "onAfterRender", {
  73641. set: function (callback) {
  73642. if (this._onAfterRenderObserver) {
  73643. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  73644. }
  73645. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  73646. },
  73647. enumerable: true,
  73648. configurable: true
  73649. });
  73650. Layer.prototype._createIndexBuffer = function () {
  73651. var engine = this._scene.getEngine();
  73652. // Indices
  73653. var indices = [];
  73654. indices.push(0);
  73655. indices.push(1);
  73656. indices.push(2);
  73657. indices.push(0);
  73658. indices.push(2);
  73659. indices.push(3);
  73660. this._indexBuffer = engine.createIndexBuffer(indices);
  73661. };
  73662. Layer.prototype._rebuild = function () {
  73663. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73664. if (vb) {
  73665. vb._rebuild();
  73666. }
  73667. this._createIndexBuffer();
  73668. };
  73669. Layer.prototype.render = function () {
  73670. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  73671. // Check
  73672. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  73673. return;
  73674. var engine = this._scene.getEngine();
  73675. this.onBeforeRenderObservable.notifyObservers(this);
  73676. // Render
  73677. engine.enableEffect(currentEffect);
  73678. engine.setState(false);
  73679. // Texture
  73680. currentEffect.setTexture("textureSampler", this.texture);
  73681. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  73682. // Color
  73683. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  73684. // Scale / offset
  73685. currentEffect.setVector2("offset", this.offset);
  73686. currentEffect.setVector2("scale", this.scale);
  73687. // VBOs
  73688. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  73689. // Draw order
  73690. if (!this.alphaTest) {
  73691. engine.setAlphaMode(this.alphaBlendingMode);
  73692. engine.draw(true, 0, 6);
  73693. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73694. }
  73695. else {
  73696. engine.draw(true, 0, 6);
  73697. }
  73698. this.onAfterRenderObservable.notifyObservers(this);
  73699. };
  73700. Layer.prototype.dispose = function () {
  73701. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73702. if (vertexBuffer) {
  73703. vertexBuffer.dispose();
  73704. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73705. }
  73706. if (this._indexBuffer) {
  73707. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73708. this._indexBuffer = null;
  73709. }
  73710. if (this.texture) {
  73711. this.texture.dispose();
  73712. this.texture = null;
  73713. }
  73714. // Remove from scene
  73715. var index = this._scene.layers.indexOf(this);
  73716. this._scene.layers.splice(index, 1);
  73717. // Callback
  73718. this.onDisposeObservable.notifyObservers(this);
  73719. this.onDisposeObservable.clear();
  73720. this.onAfterRenderObservable.clear();
  73721. this.onBeforeRenderObservable.clear();
  73722. };
  73723. return Layer;
  73724. }());
  73725. BABYLON.Layer = Layer;
  73726. })(BABYLON || (BABYLON = {}));
  73727. //# sourceMappingURL=babylon.layer.js.map
  73728. var BABYLON;
  73729. (function (BABYLON) {
  73730. var TextureTools = /** @class */ (function () {
  73731. function TextureTools() {
  73732. }
  73733. /**
  73734. * Uses the GPU to create a copy texture rescaled at a given size
  73735. * @param texture Texture to copy from
  73736. * @param width Desired width
  73737. * @param height Desired height
  73738. * @return Generated texture
  73739. */
  73740. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  73741. if (useBilinearMode === void 0) { useBilinearMode = true; }
  73742. var scene = texture.getScene();
  73743. var engine = scene.getEngine();
  73744. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  73745. rtt.wrapU = texture.wrapU;
  73746. rtt.wrapV = texture.wrapV;
  73747. rtt.uOffset = texture.uOffset;
  73748. rtt.vOffset = texture.vOffset;
  73749. rtt.uScale = texture.uScale;
  73750. rtt.vScale = texture.vScale;
  73751. rtt.uAng = texture.uAng;
  73752. rtt.vAng = texture.vAng;
  73753. rtt.wAng = texture.wAng;
  73754. rtt.coordinatesIndex = texture.coordinatesIndex;
  73755. rtt.level = texture.level;
  73756. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  73757. rtt._texture.isReady = false;
  73758. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73759. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73760. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  73761. passPostProcess.getEffect().executeWhenCompiled(function () {
  73762. passPostProcess.onApply = function (effect) {
  73763. effect.setTexture("textureSampler", texture);
  73764. };
  73765. var internalTexture = rtt.getInternalTexture();
  73766. if (internalTexture) {
  73767. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  73768. engine.unBindFramebuffer(internalTexture);
  73769. rtt.disposeFramebufferObjects();
  73770. passPostProcess.dispose();
  73771. internalTexture.isReady = true;
  73772. }
  73773. });
  73774. return rtt;
  73775. };
  73776. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  73777. if (!scene._environmentBRDFTexture) {
  73778. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73779. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73780. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73781. scene._environmentBRDFTexture = texture;
  73782. }
  73783. return scene._environmentBRDFTexture;
  73784. };
  73785. 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=";
  73786. return TextureTools;
  73787. }());
  73788. BABYLON.TextureTools = TextureTools;
  73789. })(BABYLON || (BABYLON = {}));
  73790. //# sourceMappingURL=babylon.textureTools.js.map
  73791. var BABYLON;
  73792. (function (BABYLON) {
  73793. var FramingBehavior = /** @class */ (function () {
  73794. function FramingBehavior() {
  73795. this._mode = FramingBehavior.FitFrustumSidesMode;
  73796. this._radiusScale = 1.0;
  73797. this._positionScale = 0.5;
  73798. this._defaultElevation = 0.3;
  73799. this._elevationReturnTime = 1500;
  73800. this._elevationReturnWaitTime = 1000;
  73801. this._zoomStopsAnimation = false;
  73802. this._framingTime = 1500;
  73803. this._isPointerDown = false;
  73804. this._lastInteractionTime = -Infinity;
  73805. // Framing control
  73806. this._animatables = new Array();
  73807. this._betaIsAnimating = false;
  73808. }
  73809. Object.defineProperty(FramingBehavior.prototype, "name", {
  73810. get: function () {
  73811. return "Framing";
  73812. },
  73813. enumerable: true,
  73814. configurable: true
  73815. });
  73816. Object.defineProperty(FramingBehavior.prototype, "mode", {
  73817. /**
  73818. * Gets current mode used by the behavior.
  73819. */
  73820. get: function () {
  73821. return this._mode;
  73822. },
  73823. /**
  73824. * Sets the current mode used by the behavior
  73825. */
  73826. set: function (mode) {
  73827. this._mode = mode;
  73828. },
  73829. enumerable: true,
  73830. configurable: true
  73831. });
  73832. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  73833. /**
  73834. * Gets the scale applied to the radius
  73835. */
  73836. get: function () {
  73837. return this._radiusScale;
  73838. },
  73839. /**
  73840. * Sets the scale applied to the radius (1 by default)
  73841. */
  73842. set: function (radius) {
  73843. this._radiusScale = radius;
  73844. },
  73845. enumerable: true,
  73846. configurable: true
  73847. });
  73848. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  73849. /**
  73850. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73851. */
  73852. get: function () {
  73853. return this._positionScale;
  73854. },
  73855. /**
  73856. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  73857. */
  73858. set: function (scale) {
  73859. this._positionScale = scale;
  73860. },
  73861. enumerable: true,
  73862. configurable: true
  73863. });
  73864. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  73865. /**
  73866. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73867. * behaviour is triggered, in radians.
  73868. */
  73869. get: function () {
  73870. return this._defaultElevation;
  73871. },
  73872. /**
  73873. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  73874. * behaviour is triggered, in radians.
  73875. */
  73876. set: function (elevation) {
  73877. this._defaultElevation = elevation;
  73878. },
  73879. enumerable: true,
  73880. configurable: true
  73881. });
  73882. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  73883. /**
  73884. * Gets the time (in milliseconds) taken to return to the default beta position.
  73885. * Negative value indicates camera should not return to default.
  73886. */
  73887. get: function () {
  73888. return this._elevationReturnTime;
  73889. },
  73890. /**
  73891. * Sets the time (in milliseconds) taken to return to the default beta position.
  73892. * Negative value indicates camera should not return to default.
  73893. */
  73894. set: function (speed) {
  73895. this._elevationReturnTime = speed;
  73896. },
  73897. enumerable: true,
  73898. configurable: true
  73899. });
  73900. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  73901. /**
  73902. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73903. */
  73904. get: function () {
  73905. return this._elevationReturnWaitTime;
  73906. },
  73907. /**
  73908. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  73909. */
  73910. set: function (time) {
  73911. this._elevationReturnWaitTime = time;
  73912. },
  73913. enumerable: true,
  73914. configurable: true
  73915. });
  73916. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  73917. /**
  73918. * Gets the flag that indicates if user zooming should stop animation.
  73919. */
  73920. get: function () {
  73921. return this._zoomStopsAnimation;
  73922. },
  73923. /**
  73924. * Sets the flag that indicates if user zooming should stop animation.
  73925. */
  73926. set: function (flag) {
  73927. this._zoomStopsAnimation = flag;
  73928. },
  73929. enumerable: true,
  73930. configurable: true
  73931. });
  73932. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  73933. /**
  73934. * Gets the transition time when framing the mesh, in milliseconds
  73935. */
  73936. get: function () {
  73937. return this._framingTime;
  73938. },
  73939. /**
  73940. * Sets the transition time when framing the mesh, in milliseconds
  73941. */
  73942. set: function (time) {
  73943. this._framingTime = time;
  73944. },
  73945. enumerable: true,
  73946. configurable: true
  73947. });
  73948. FramingBehavior.prototype.init = function () {
  73949. // Do notihng
  73950. };
  73951. FramingBehavior.prototype.attach = function (camera) {
  73952. var _this = this;
  73953. this._attachedCamera = camera;
  73954. var scene = this._attachedCamera.getScene();
  73955. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  73956. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  73957. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  73958. _this._isPointerDown = true;
  73959. return;
  73960. }
  73961. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  73962. _this._isPointerDown = false;
  73963. }
  73964. });
  73965. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  73966. if (mesh) {
  73967. _this.zoomOnMesh(mesh);
  73968. }
  73969. });
  73970. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  73971. // Stop the animation if there is user interaction and the animation should stop for this interaction
  73972. _this._applyUserInteraction();
  73973. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  73974. // back to the default position after a given timeout
  73975. _this._maintainCameraAboveGround();
  73976. });
  73977. };
  73978. FramingBehavior.prototype.detach = function () {
  73979. if (!this._attachedCamera) {
  73980. return;
  73981. }
  73982. var scene = this._attachedCamera.getScene();
  73983. if (this._onPrePointerObservableObserver) {
  73984. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  73985. }
  73986. if (this._onAfterCheckInputsObserver) {
  73987. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  73988. }
  73989. if (this._onMeshTargetChangedObserver) {
  73990. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  73991. }
  73992. this._attachedCamera = null;
  73993. };
  73994. /**
  73995. * Targets the given mesh and updates zoom level accordingly.
  73996. * @param mesh The mesh to target.
  73997. * @param radius Optional. If a cached radius position already exists, overrides default.
  73998. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  73999. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  74000. * @param onAnimationEnd Callback triggered at the end of the framing animation
  74001. */
  74002. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  74003. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  74004. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  74005. mesh.computeWorldMatrix(true);
  74006. var boundingBox = mesh.getBoundingInfo().boundingBox;
  74007. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  74008. };
  74009. /**
  74010. * Targets the given mesh and updates zoom level accordingly.
  74011. * @param mesh The mesh to target.
  74012. * @param radius Optional. If a cached radius position already exists, overrides default.
  74013. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  74014. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  74015. * @param onAnimationEnd Callback triggered at the end of the framing animation
  74016. */
  74017. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  74018. var _this = this;
  74019. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  74020. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  74021. var zoomTarget;
  74022. if (!this._attachedCamera) {
  74023. return;
  74024. }
  74025. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  74026. var bottom = minimumWorld.y;
  74027. var top = maximumWorld.y;
  74028. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  74029. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  74030. if (focusOnOriginXZ) {
  74031. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  74032. }
  74033. else {
  74034. var centerWorld = minimumWorld.add(radiusWorld);
  74035. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  74036. }
  74037. if (!this._vectorTransition) {
  74038. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  74039. }
  74040. this._betaIsAnimating = true;
  74041. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  74042. if (animatable) {
  74043. this._animatables.push(animatable);
  74044. }
  74045. // sets the radius and lower radius bounds
  74046. // Small delta ensures camera is not always at lower zoom limit.
  74047. var radius = 0;
  74048. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  74049. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  74050. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  74051. radius = position;
  74052. }
  74053. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  74054. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  74055. if (this._attachedCamera.lowerRadiusLimit === null) {
  74056. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  74057. }
  74058. }
  74059. // Set sensibilities
  74060. var extend = maximumWorld.subtract(minimumWorld).length();
  74061. this._attachedCamera.panningSensibility = 5000 / extend;
  74062. this._attachedCamera.wheelPrecision = 100 / radius;
  74063. // transition to new radius
  74064. if (!this._radiusTransition) {
  74065. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  74066. }
  74067. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  74068. if (onAnimationEnd) {
  74069. onAnimationEnd();
  74070. }
  74071. if (_this._attachedCamera) {
  74072. _this._attachedCamera.storeState();
  74073. }
  74074. });
  74075. if (animatable) {
  74076. this._animatables.push(animatable);
  74077. }
  74078. };
  74079. /**
  74080. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  74081. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  74082. * frustum width.
  74083. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  74084. * to fully enclose the mesh in the viewing frustum.
  74085. */
  74086. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  74087. var size = maximumWorld.subtract(minimumWorld);
  74088. var boxVectorGlobalDiagonal = size.length();
  74089. var frustumSlope = this._getFrustumSlope();
  74090. // Formula for setting distance
  74091. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  74092. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  74093. // Horizon distance
  74094. var radius = radiusWithoutFraming * this._radiusScale;
  74095. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  74096. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  74097. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  74098. var camera = this._attachedCamera;
  74099. if (!camera) {
  74100. return 0;
  74101. }
  74102. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  74103. // Don't exceed the requested limit
  74104. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  74105. }
  74106. // Don't exceed the upper radius limit
  74107. if (camera.upperRadiusLimit) {
  74108. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  74109. }
  74110. return distance;
  74111. };
  74112. /**
  74113. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  74114. * is automatically returned to its default position (expected to be above ground plane).
  74115. */
  74116. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  74117. var _this = this;
  74118. if (this._elevationReturnTime < 0) {
  74119. return;
  74120. }
  74121. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  74122. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  74123. var limitBeta = Math.PI * 0.5;
  74124. // Bring the camera back up if below the ground plane
  74125. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  74126. this._betaIsAnimating = true;
  74127. //Transition to new position
  74128. this.stopAllAnimations();
  74129. if (!this._betaTransition) {
  74130. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  74131. }
  74132. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  74133. _this._clearAnimationLocks();
  74134. _this.stopAllAnimations();
  74135. });
  74136. if (animatabe) {
  74137. this._animatables.push(animatabe);
  74138. }
  74139. }
  74140. };
  74141. /**
  74142. * Returns the frustum slope based on the canvas ratio and camera FOV
  74143. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  74144. */
  74145. FramingBehavior.prototype._getFrustumSlope = function () {
  74146. // Calculate the viewport ratio
  74147. // Aspect Ratio is Height/Width.
  74148. var camera = this._attachedCamera;
  74149. if (!camera) {
  74150. return BABYLON.Vector2.Zero();
  74151. }
  74152. var engine = camera.getScene().getEngine();
  74153. var aspectRatio = engine.getAspectRatio(camera);
  74154. // Camera FOV is the vertical field of view (top-bottom) in radians.
  74155. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  74156. var frustumSlopeY = Math.tan(camera.fov / 2);
  74157. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  74158. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  74159. // along the forward vector.
  74160. var frustumSlopeX = frustumSlopeY * aspectRatio;
  74161. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  74162. };
  74163. /**
  74164. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  74165. */
  74166. FramingBehavior.prototype._clearAnimationLocks = function () {
  74167. this._betaIsAnimating = false;
  74168. };
  74169. /**
  74170. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74171. */
  74172. FramingBehavior.prototype._applyUserInteraction = function () {
  74173. if (this.isUserIsMoving) {
  74174. this._lastInteractionTime = BABYLON.Tools.Now;
  74175. this.stopAllAnimations();
  74176. this._clearAnimationLocks();
  74177. }
  74178. };
  74179. /**
  74180. * Stops and removes all animations that have been applied to the camera
  74181. */
  74182. FramingBehavior.prototype.stopAllAnimations = function () {
  74183. if (this._attachedCamera) {
  74184. this._attachedCamera.animations = [];
  74185. }
  74186. while (this._animatables.length) {
  74187. if (this._animatables[0]) {
  74188. this._animatables[0].onAnimationEnd = null;
  74189. this._animatables[0].stop();
  74190. }
  74191. this._animatables.shift();
  74192. }
  74193. };
  74194. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  74195. /**
  74196. * Gets a value indicating if the user is moving the camera
  74197. */
  74198. get: function () {
  74199. if (!this._attachedCamera) {
  74200. return false;
  74201. }
  74202. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74203. this._attachedCamera.inertialBetaOffset !== 0 ||
  74204. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74205. this._attachedCamera.inertialPanningX !== 0 ||
  74206. this._attachedCamera.inertialPanningY !== 0 ||
  74207. this._isPointerDown;
  74208. },
  74209. enumerable: true,
  74210. configurable: true
  74211. });
  74212. /**
  74213. * The easing function used by animations
  74214. */
  74215. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  74216. /**
  74217. * The easing mode used by animations
  74218. */
  74219. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  74220. // Statics
  74221. /**
  74222. * The camera can move all the way towards the mesh.
  74223. */
  74224. FramingBehavior.IgnoreBoundsSizeMode = 0;
  74225. /**
  74226. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  74227. */
  74228. FramingBehavior.FitFrustumSidesMode = 1;
  74229. return FramingBehavior;
  74230. }());
  74231. BABYLON.FramingBehavior = FramingBehavior;
  74232. })(BABYLON || (BABYLON = {}));
  74233. //# sourceMappingURL=babylon.framingBehavior.js.map
  74234. var BABYLON;
  74235. (function (BABYLON) {
  74236. /**
  74237. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  74238. */
  74239. var BouncingBehavior = /** @class */ (function () {
  74240. function BouncingBehavior() {
  74241. /**
  74242. * The duration of the animation, in milliseconds
  74243. */
  74244. this.transitionDuration = 450;
  74245. /**
  74246. * Length of the distance animated by the transition when lower radius is reached
  74247. */
  74248. this.lowerRadiusTransitionRange = 2;
  74249. /**
  74250. * Length of the distance animated by the transition when upper radius is reached
  74251. */
  74252. this.upperRadiusTransitionRange = -2;
  74253. this._autoTransitionRange = false;
  74254. // Animations
  74255. this._radiusIsAnimating = false;
  74256. this._radiusBounceTransition = null;
  74257. this._animatables = new Array();
  74258. }
  74259. Object.defineProperty(BouncingBehavior.prototype, "name", {
  74260. get: function () {
  74261. return "Bouncing";
  74262. },
  74263. enumerable: true,
  74264. configurable: true
  74265. });
  74266. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  74267. /**
  74268. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  74269. */
  74270. get: function () {
  74271. return this._autoTransitionRange;
  74272. },
  74273. /**
  74274. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  74275. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  74276. */
  74277. set: function (value) {
  74278. var _this = this;
  74279. if (this._autoTransitionRange === value) {
  74280. return;
  74281. }
  74282. this._autoTransitionRange = value;
  74283. var camera = this._attachedCamera;
  74284. if (!camera) {
  74285. return;
  74286. }
  74287. if (value) {
  74288. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  74289. if (!mesh) {
  74290. return;
  74291. }
  74292. mesh.computeWorldMatrix(true);
  74293. var diagonal = mesh.getBoundingInfo().diagonalLength;
  74294. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  74295. _this.upperRadiusTransitionRange = diagonal * 0.05;
  74296. });
  74297. }
  74298. else if (this._onMeshTargetChangedObserver) {
  74299. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74300. }
  74301. },
  74302. enumerable: true,
  74303. configurable: true
  74304. });
  74305. BouncingBehavior.prototype.init = function () {
  74306. // Do notihng
  74307. };
  74308. BouncingBehavior.prototype.attach = function (camera) {
  74309. var _this = this;
  74310. this._attachedCamera = camera;
  74311. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74312. if (!_this._attachedCamera) {
  74313. return;
  74314. }
  74315. // Add the bounce animation to the lower radius limit
  74316. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  74317. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  74318. }
  74319. // Add the bounce animation to the upper radius limit
  74320. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  74321. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  74322. }
  74323. });
  74324. };
  74325. BouncingBehavior.prototype.detach = function () {
  74326. if (!this._attachedCamera) {
  74327. return;
  74328. }
  74329. if (this._onAfterCheckInputsObserver) {
  74330. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74331. }
  74332. if (this._onMeshTargetChangedObserver) {
  74333. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  74334. }
  74335. this._attachedCamera = null;
  74336. };
  74337. /**
  74338. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  74339. * @param radiusLimit The limit to check against.
  74340. * @return Bool to indicate if at limit.
  74341. */
  74342. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  74343. if (!this._attachedCamera) {
  74344. return false;
  74345. }
  74346. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  74347. return true;
  74348. }
  74349. return false;
  74350. };
  74351. /**
  74352. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  74353. * @param radiusDelta The delta by which to animate to. Can be negative.
  74354. */
  74355. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  74356. var _this = this;
  74357. if (!this._attachedCamera) {
  74358. return;
  74359. }
  74360. if (!this._radiusBounceTransition) {
  74361. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  74362. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  74363. }
  74364. // Prevent zoom until bounce has completed
  74365. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  74366. this._attachedCamera.wheelPrecision = Infinity;
  74367. this._attachedCamera.inertialRadiusOffset = 0;
  74368. // Animate to the radius limit
  74369. this.stopAllAnimations();
  74370. this._radiusIsAnimating = true;
  74371. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  74372. if (animatable) {
  74373. this._animatables.push(animatable);
  74374. }
  74375. };
  74376. /**
  74377. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  74378. */
  74379. BouncingBehavior.prototype._clearAnimationLocks = function () {
  74380. this._radiusIsAnimating = false;
  74381. if (this._attachedCamera) {
  74382. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  74383. }
  74384. };
  74385. /**
  74386. * Stops and removes all animations that have been applied to the camera
  74387. */
  74388. BouncingBehavior.prototype.stopAllAnimations = function () {
  74389. if (this._attachedCamera) {
  74390. this._attachedCamera.animations = [];
  74391. }
  74392. while (this._animatables.length) {
  74393. this._animatables[0].onAnimationEnd = null;
  74394. this._animatables[0].stop();
  74395. this._animatables.shift();
  74396. }
  74397. };
  74398. /**
  74399. * The easing function used by animations
  74400. */
  74401. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  74402. /**
  74403. * The easing mode used by animations
  74404. */
  74405. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  74406. return BouncingBehavior;
  74407. }());
  74408. BABYLON.BouncingBehavior = BouncingBehavior;
  74409. })(BABYLON || (BABYLON = {}));
  74410. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  74411. var BABYLON;
  74412. (function (BABYLON) {
  74413. var AutoRotationBehavior = /** @class */ (function () {
  74414. function AutoRotationBehavior() {
  74415. this._zoomStopsAnimation = false;
  74416. this._idleRotationSpeed = 0.05;
  74417. this._idleRotationWaitTime = 2000;
  74418. this._idleRotationSpinupTime = 2000;
  74419. this._isPointerDown = false;
  74420. this._lastFrameTime = null;
  74421. this._lastInteractionTime = -Infinity;
  74422. this._cameraRotationSpeed = 0;
  74423. this._lastFrameRadius = 0;
  74424. }
  74425. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  74426. get: function () {
  74427. return "AutoRotation";
  74428. },
  74429. enumerable: true,
  74430. configurable: true
  74431. });
  74432. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  74433. /**
  74434. * Gets the flag that indicates if user zooming should stop animation.
  74435. */
  74436. get: function () {
  74437. return this._zoomStopsAnimation;
  74438. },
  74439. /**
  74440. * Sets the flag that indicates if user zooming should stop animation.
  74441. */
  74442. set: function (flag) {
  74443. this._zoomStopsAnimation = flag;
  74444. },
  74445. enumerable: true,
  74446. configurable: true
  74447. });
  74448. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  74449. /**
  74450. * Gets the default speed at which the camera rotates around the model.
  74451. */
  74452. get: function () {
  74453. return this._idleRotationSpeed;
  74454. },
  74455. /**
  74456. * Sets the default speed at which the camera rotates around the model.
  74457. */
  74458. set: function (speed) {
  74459. this._idleRotationSpeed = speed;
  74460. },
  74461. enumerable: true,
  74462. configurable: true
  74463. });
  74464. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  74465. /**
  74466. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  74467. */
  74468. get: function () {
  74469. return this._idleRotationWaitTime;
  74470. },
  74471. /**
  74472. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  74473. */
  74474. set: function (time) {
  74475. this._idleRotationWaitTime = time;
  74476. },
  74477. enumerable: true,
  74478. configurable: true
  74479. });
  74480. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  74481. /**
  74482. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74483. */
  74484. get: function () {
  74485. return this._idleRotationSpinupTime;
  74486. },
  74487. /**
  74488. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  74489. */
  74490. set: function (time) {
  74491. this._idleRotationSpinupTime = time;
  74492. },
  74493. enumerable: true,
  74494. configurable: true
  74495. });
  74496. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  74497. /**
  74498. * Gets a value indicating if the camera is currently rotating because of this behavior
  74499. */
  74500. get: function () {
  74501. return Math.abs(this._cameraRotationSpeed) > 0;
  74502. },
  74503. enumerable: true,
  74504. configurable: true
  74505. });
  74506. AutoRotationBehavior.prototype.init = function () {
  74507. // Do notihng
  74508. };
  74509. AutoRotationBehavior.prototype.attach = function (camera) {
  74510. var _this = this;
  74511. this._attachedCamera = camera;
  74512. var scene = this._attachedCamera.getScene();
  74513. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  74514. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  74515. _this._isPointerDown = true;
  74516. return;
  74517. }
  74518. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  74519. _this._isPointerDown = false;
  74520. }
  74521. });
  74522. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  74523. var now = BABYLON.Tools.Now;
  74524. var dt = 0;
  74525. if (_this._lastFrameTime != null) {
  74526. dt = now - _this._lastFrameTime;
  74527. }
  74528. _this._lastFrameTime = now;
  74529. // Stop the animation if there is user interaction and the animation should stop for this interaction
  74530. _this._applyUserInteraction();
  74531. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  74532. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  74533. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  74534. // Step camera rotation by rotation speed
  74535. if (_this._attachedCamera) {
  74536. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  74537. }
  74538. });
  74539. };
  74540. AutoRotationBehavior.prototype.detach = function () {
  74541. if (!this._attachedCamera) {
  74542. return;
  74543. }
  74544. var scene = this._attachedCamera.getScene();
  74545. if (this._onPrePointerObservableObserver) {
  74546. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  74547. }
  74548. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  74549. this._attachedCamera = null;
  74550. };
  74551. /**
  74552. * Returns true if user is scrolling.
  74553. * @return true if user is scrolling.
  74554. */
  74555. AutoRotationBehavior.prototype._userIsZooming = function () {
  74556. if (!this._attachedCamera) {
  74557. return false;
  74558. }
  74559. return this._attachedCamera.inertialRadiusOffset !== 0;
  74560. };
  74561. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  74562. if (!this._attachedCamera) {
  74563. return false;
  74564. }
  74565. var zoomHasHitLimit = false;
  74566. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  74567. zoomHasHitLimit = true;
  74568. }
  74569. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  74570. this._lastFrameRadius = this._attachedCamera.radius;
  74571. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  74572. };
  74573. /**
  74574. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  74575. */
  74576. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  74577. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  74578. this._lastInteractionTime = BABYLON.Tools.Now;
  74579. }
  74580. };
  74581. // Tools
  74582. AutoRotationBehavior.prototype._userIsMoving = function () {
  74583. if (!this._attachedCamera) {
  74584. return false;
  74585. }
  74586. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  74587. this._attachedCamera.inertialBetaOffset !== 0 ||
  74588. this._attachedCamera.inertialRadiusOffset !== 0 ||
  74589. this._attachedCamera.inertialPanningX !== 0 ||
  74590. this._attachedCamera.inertialPanningY !== 0 ||
  74591. this._isPointerDown;
  74592. };
  74593. return AutoRotationBehavior;
  74594. }());
  74595. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  74596. })(BABYLON || (BABYLON = {}));
  74597. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  74598. var BABYLON;
  74599. (function (BABYLON) {
  74600. var NullEngineOptions = /** @class */ (function () {
  74601. function NullEngineOptions() {
  74602. this.renderWidth = 512;
  74603. this.renderHeight = 256;
  74604. this.textureSize = 512;
  74605. }
  74606. return NullEngineOptions;
  74607. }());
  74608. BABYLON.NullEngineOptions = NullEngineOptions;
  74609. /**
  74610. * The null engine class provides support for headless version of babylon.js.
  74611. * This can be used in server side scenario or for testing purposes
  74612. */
  74613. var NullEngine = /** @class */ (function (_super) {
  74614. __extends(NullEngine, _super);
  74615. function NullEngine(options) {
  74616. if (options === void 0) { options = new NullEngineOptions(); }
  74617. var _this = _super.call(this, null) || this;
  74618. _this._options = options;
  74619. // Init caps
  74620. // We consider we are on a webgl1 capable device
  74621. _this._caps = new BABYLON.EngineCapabilities();
  74622. _this._caps.maxTexturesImageUnits = 16;
  74623. _this._caps.maxVertexTextureImageUnits = 16;
  74624. _this._caps.maxTextureSize = 512;
  74625. _this._caps.maxCubemapTextureSize = 512;
  74626. _this._caps.maxRenderTextureSize = 512;
  74627. _this._caps.maxVertexAttribs = 16;
  74628. _this._caps.maxVaryingVectors = 16;
  74629. _this._caps.maxFragmentUniformVectors = 16;
  74630. _this._caps.maxVertexUniformVectors = 16;
  74631. // Extensions
  74632. _this._caps.standardDerivatives = false;
  74633. _this._caps.astc = null;
  74634. _this._caps.s3tc = null;
  74635. _this._caps.pvrtc = null;
  74636. _this._caps.etc1 = null;
  74637. _this._caps.etc2 = null;
  74638. _this._caps.textureAnisotropicFilterExtension = null;
  74639. _this._caps.maxAnisotropy = 0;
  74640. _this._caps.uintIndices = false;
  74641. _this._caps.fragmentDepthSupported = false;
  74642. _this._caps.highPrecisionShaderSupported = true;
  74643. _this._caps.colorBufferFloat = false;
  74644. _this._caps.textureFloat = false;
  74645. _this._caps.textureFloatLinearFiltering = false;
  74646. _this._caps.textureFloatRender = false;
  74647. _this._caps.textureHalfFloat = false;
  74648. _this._caps.textureHalfFloatLinearFiltering = false;
  74649. _this._caps.textureHalfFloatRender = false;
  74650. _this._caps.textureLOD = false;
  74651. _this._caps.drawBuffersExtension = false;
  74652. _this._caps.depthTextureExtension = false;
  74653. _this._caps.vertexArrayObject = false;
  74654. _this._caps.instancedArrays = false;
  74655. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  74656. // Wrappers
  74657. if (typeof URL === "undefined") {
  74658. URL = {
  74659. createObjectURL: function () { },
  74660. revokeObjectURL: function () { }
  74661. };
  74662. }
  74663. if (typeof Blob === "undefined") {
  74664. Blob = function () { };
  74665. }
  74666. return _this;
  74667. }
  74668. NullEngine.prototype.createVertexBuffer = function (vertices) {
  74669. return {
  74670. capacity: 0,
  74671. references: 1,
  74672. is32Bits: false
  74673. };
  74674. };
  74675. NullEngine.prototype.createIndexBuffer = function (indices) {
  74676. return {
  74677. capacity: 0,
  74678. references: 1,
  74679. is32Bits: false
  74680. };
  74681. };
  74682. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  74683. if (stencil === void 0) { stencil = false; }
  74684. };
  74685. NullEngine.prototype.getRenderWidth = function (useScreen) {
  74686. if (useScreen === void 0) { useScreen = false; }
  74687. if (!useScreen && this._currentRenderTarget) {
  74688. return this._currentRenderTarget.width;
  74689. }
  74690. return this._options.renderWidth;
  74691. };
  74692. NullEngine.prototype.getRenderHeight = function (useScreen) {
  74693. if (useScreen === void 0) { useScreen = false; }
  74694. if (!useScreen && this._currentRenderTarget) {
  74695. return this._currentRenderTarget.height;
  74696. }
  74697. return this._options.renderHeight;
  74698. };
  74699. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  74700. this._cachedViewport = viewport;
  74701. };
  74702. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  74703. return {
  74704. transformFeedback: null,
  74705. __SPECTOR_rebuildProgram: null
  74706. };
  74707. };
  74708. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  74709. return [];
  74710. };
  74711. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  74712. return [];
  74713. };
  74714. NullEngine.prototype.bindSamplers = function (effect) {
  74715. this._currentEffect = null;
  74716. };
  74717. NullEngine.prototype.enableEffect = function (effect) {
  74718. this._currentEffect = effect;
  74719. if (effect.onBind) {
  74720. effect.onBind(effect);
  74721. }
  74722. effect.onBindObservable.notifyObservers(effect);
  74723. };
  74724. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  74725. if (zOffset === void 0) { zOffset = 0; }
  74726. if (reverseSide === void 0) { reverseSide = false; }
  74727. };
  74728. NullEngine.prototype.setIntArray = function (uniform, array) {
  74729. };
  74730. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  74731. };
  74732. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  74733. };
  74734. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  74735. };
  74736. NullEngine.prototype.setFloatArray = function (uniform, array) {
  74737. };
  74738. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  74739. };
  74740. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  74741. };
  74742. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  74743. };
  74744. NullEngine.prototype.setArray = function (uniform, array) {
  74745. };
  74746. NullEngine.prototype.setArray2 = function (uniform, array) {
  74747. };
  74748. NullEngine.prototype.setArray3 = function (uniform, array) {
  74749. };
  74750. NullEngine.prototype.setArray4 = function (uniform, array) {
  74751. };
  74752. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  74753. };
  74754. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  74755. };
  74756. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  74757. };
  74758. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  74759. };
  74760. NullEngine.prototype.setFloat = function (uniform, value) {
  74761. };
  74762. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  74763. };
  74764. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  74765. };
  74766. NullEngine.prototype.setBool = function (uniform, bool) {
  74767. };
  74768. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  74769. };
  74770. NullEngine.prototype.setColor3 = function (uniform, color3) {
  74771. };
  74772. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  74773. };
  74774. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  74775. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  74776. if (this._alphaMode === mode) {
  74777. return;
  74778. }
  74779. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  74780. if (!noDepthWriteChange) {
  74781. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  74782. }
  74783. this._alphaMode = mode;
  74784. };
  74785. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  74786. };
  74787. NullEngine.prototype.wipeCaches = function (bruteForce) {
  74788. if (this.preventCacheWipeBetweenFrames) {
  74789. return;
  74790. }
  74791. this.resetTextureCache();
  74792. this._currentEffect = null;
  74793. if (bruteForce) {
  74794. this._currentProgram = null;
  74795. this._stencilState.reset();
  74796. this._depthCullingState.reset();
  74797. this.setDepthFunctionToLessOrEqual();
  74798. this._alphaState.reset();
  74799. }
  74800. this._cachedVertexBuffers = null;
  74801. this._cachedIndexBuffer = null;
  74802. this._cachedEffectForVertexBuffers = null;
  74803. };
  74804. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  74805. };
  74806. NullEngine.prototype._createTexture = function () {
  74807. return {};
  74808. };
  74809. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  74810. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  74811. if (onLoad === void 0) { onLoad = null; }
  74812. if (onError === void 0) { onError = null; }
  74813. if (buffer === void 0) { buffer = null; }
  74814. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  74815. var url = String(urlArg);
  74816. texture.url = url;
  74817. texture.generateMipMaps = !noMipmap;
  74818. texture.samplingMode = samplingMode;
  74819. texture.invertY = invertY;
  74820. texture.baseWidth = this._options.textureSize;
  74821. texture.baseHeight = this._options.textureSize;
  74822. texture.width = this._options.textureSize;
  74823. texture.height = this._options.textureSize;
  74824. if (format) {
  74825. texture.format = format;
  74826. }
  74827. texture.isReady = true;
  74828. if (onLoad) {
  74829. onLoad();
  74830. }
  74831. return texture;
  74832. };
  74833. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  74834. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  74835. if (options !== undefined && typeof options === "object") {
  74836. fullOptions.generateMipMaps = options.generateMipMaps;
  74837. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  74838. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  74839. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  74840. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  74841. }
  74842. else {
  74843. fullOptions.generateMipMaps = options;
  74844. fullOptions.generateDepthBuffer = true;
  74845. fullOptions.generateStencilBuffer = false;
  74846. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74847. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  74848. }
  74849. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  74850. var width = size.width || size;
  74851. var height = size.height || size;
  74852. texture._depthStencilBuffer = {};
  74853. texture._framebuffer = {};
  74854. texture.baseWidth = width;
  74855. texture.baseHeight = height;
  74856. texture.width = width;
  74857. texture.height = height;
  74858. texture.isReady = true;
  74859. texture.samples = 1;
  74860. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  74861. texture.samplingMode = fullOptions.samplingMode;
  74862. texture.type = fullOptions.type;
  74863. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  74864. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  74865. return texture;
  74866. };
  74867. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  74868. texture.samplingMode = samplingMode;
  74869. };
  74870. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  74871. if (this._currentRenderTarget) {
  74872. this.unBindFramebuffer(this._currentRenderTarget);
  74873. }
  74874. this._currentRenderTarget = texture;
  74875. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  74876. if (this._cachedViewport && !forceFullscreenViewport) {
  74877. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  74878. }
  74879. };
  74880. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  74881. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  74882. this._currentRenderTarget = null;
  74883. if (onBeforeUnbind) {
  74884. if (texture._MSAAFramebuffer) {
  74885. this._currentFramebuffer = texture._framebuffer;
  74886. }
  74887. onBeforeUnbind();
  74888. }
  74889. this._currentFramebuffer = null;
  74890. };
  74891. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  74892. var vbo = {
  74893. capacity: 1,
  74894. references: 1,
  74895. is32Bits: false
  74896. };
  74897. return vbo;
  74898. };
  74899. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  74900. if (offset === void 0) { offset = 0; }
  74901. };
  74902. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  74903. };
  74904. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  74905. if (this._activeTexturesCache[this._activeTextureChannel] !== texture) {
  74906. this._activeTexturesCache[this._activeTextureChannel] = texture;
  74907. }
  74908. };
  74909. NullEngine.prototype._bindTexture = function (channel, texture) {
  74910. if (channel < 0) {
  74911. return;
  74912. }
  74913. this._bindTextureDirectly(0, texture);
  74914. };
  74915. return NullEngine;
  74916. }(BABYLON.Engine));
  74917. BABYLON.NullEngine = NullEngine;
  74918. })(BABYLON || (BABYLON = {}));
  74919. //# sourceMappingURL=babylon.nullEngine.js.map
  74920. var BABYLON;
  74921. (function (BABYLON) {
  74922. /**
  74923. * This class can be used to get instrumentation data from a Babylon engine
  74924. */
  74925. var EngineInstrumentation = /** @class */ (function () {
  74926. function EngineInstrumentation(engine) {
  74927. this.engine = engine;
  74928. this._captureGPUFrameTime = false;
  74929. this._gpuFrameTime = new BABYLON.PerfCounter();
  74930. this._captureShaderCompilationTime = false;
  74931. this._shaderCompilationTime = new BABYLON.PerfCounter();
  74932. // Observers
  74933. this._onBeginFrameObserver = null;
  74934. this._onEndFrameObserver = null;
  74935. this._onBeforeShaderCompilationObserver = null;
  74936. this._onAfterShaderCompilationObserver = null;
  74937. }
  74938. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  74939. // Properties
  74940. /**
  74941. * Gets the perf counter used for GPU frame time
  74942. */
  74943. get: function () {
  74944. return this._gpuFrameTime;
  74945. },
  74946. enumerable: true,
  74947. configurable: true
  74948. });
  74949. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  74950. /**
  74951. * Gets the GPU frame time capture status
  74952. */
  74953. get: function () {
  74954. return this._captureGPUFrameTime;
  74955. },
  74956. /**
  74957. * Enable or disable the GPU frame time capture
  74958. */
  74959. set: function (value) {
  74960. var _this = this;
  74961. if (value === this._captureGPUFrameTime) {
  74962. return;
  74963. }
  74964. this._captureGPUFrameTime = value;
  74965. if (value) {
  74966. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  74967. if (!_this._gpuFrameTimeToken) {
  74968. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  74969. }
  74970. });
  74971. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  74972. if (!_this._gpuFrameTimeToken) {
  74973. return;
  74974. }
  74975. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  74976. if (time > -1) {
  74977. _this._gpuFrameTimeToken = null;
  74978. _this._gpuFrameTime.fetchNewFrame();
  74979. _this._gpuFrameTime.addCount(time, true);
  74980. }
  74981. });
  74982. }
  74983. else {
  74984. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  74985. this._onBeginFrameObserver = null;
  74986. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  74987. this._onEndFrameObserver = null;
  74988. }
  74989. },
  74990. enumerable: true,
  74991. configurable: true
  74992. });
  74993. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  74994. /**
  74995. * Gets the perf counter used for shader compilation time
  74996. */
  74997. get: function () {
  74998. return this._shaderCompilationTime;
  74999. },
  75000. enumerable: true,
  75001. configurable: true
  75002. });
  75003. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  75004. /**
  75005. * Gets the shader compilation time capture status
  75006. */
  75007. get: function () {
  75008. return this._captureShaderCompilationTime;
  75009. },
  75010. /**
  75011. * Enable or disable the shader compilation time capture
  75012. */
  75013. set: function (value) {
  75014. var _this = this;
  75015. if (value === this._captureShaderCompilationTime) {
  75016. return;
  75017. }
  75018. this._captureShaderCompilationTime = value;
  75019. if (value) {
  75020. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  75021. _this._shaderCompilationTime.fetchNewFrame();
  75022. _this._shaderCompilationTime.beginMonitoring();
  75023. });
  75024. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  75025. _this._shaderCompilationTime.endMonitoring();
  75026. });
  75027. }
  75028. else {
  75029. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  75030. this._onBeforeShaderCompilationObserver = null;
  75031. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  75032. this._onAfterShaderCompilationObserver = null;
  75033. }
  75034. },
  75035. enumerable: true,
  75036. configurable: true
  75037. });
  75038. EngineInstrumentation.prototype.dispose = function () {
  75039. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  75040. this._onBeginFrameObserver = null;
  75041. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  75042. this._onEndFrameObserver = null;
  75043. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  75044. this._onBeforeShaderCompilationObserver = null;
  75045. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  75046. this._onAfterShaderCompilationObserver = null;
  75047. this.engine = null;
  75048. };
  75049. return EngineInstrumentation;
  75050. }());
  75051. BABYLON.EngineInstrumentation = EngineInstrumentation;
  75052. })(BABYLON || (BABYLON = {}));
  75053. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  75054. var BABYLON;
  75055. (function (BABYLON) {
  75056. /**
  75057. * This class can be used to get instrumentation data from a Babylon engine
  75058. */
  75059. var SceneInstrumentation = /** @class */ (function () {
  75060. function SceneInstrumentation(scene) {
  75061. var _this = this;
  75062. this.scene = scene;
  75063. this._captureActiveMeshesEvaluationTime = false;
  75064. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  75065. this._captureRenderTargetsRenderTime = false;
  75066. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  75067. this._captureFrameTime = false;
  75068. this._frameTime = new BABYLON.PerfCounter();
  75069. this._captureRenderTime = false;
  75070. this._renderTime = new BABYLON.PerfCounter();
  75071. this._captureInterFrameTime = false;
  75072. this._interFrameTime = new BABYLON.PerfCounter();
  75073. this._captureParticlesRenderTime = false;
  75074. this._particlesRenderTime = new BABYLON.PerfCounter();
  75075. this._captureSpritesRenderTime = false;
  75076. this._spritesRenderTime = new BABYLON.PerfCounter();
  75077. this._capturePhysicsTime = false;
  75078. this._physicsTime = new BABYLON.PerfCounter();
  75079. this._captureAnimationsTime = false;
  75080. this._animationsTime = new BABYLON.PerfCounter();
  75081. // Observers
  75082. this._onBeforeActiveMeshesEvaluationObserver = null;
  75083. this._onAfterActiveMeshesEvaluationObserver = null;
  75084. this._onBeforeRenderTargetsRenderObserver = null;
  75085. this._onAfterRenderTargetsRenderObserver = null;
  75086. this._onAfterRenderObserver = null;
  75087. this._onBeforeDrawPhaseObserver = null;
  75088. this._onAfterDrawPhaseObserver = null;
  75089. this._onBeforeAnimationsObserver = null;
  75090. this._onBeforeParticlesRenderingObserver = null;
  75091. this._onAfterParticlesRenderingObserver = null;
  75092. this._onBeforeSpritesRenderingObserver = null;
  75093. this._onAfterSpritesRenderingObserver = null;
  75094. this._onBeforePhysicsObserver = null;
  75095. this._onAfterPhysicsObserver = null;
  75096. this._onAfterAnimationsObserver = null;
  75097. // Before render
  75098. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  75099. if (_this._captureActiveMeshesEvaluationTime) {
  75100. _this._activeMeshesEvaluationTime.fetchNewFrame();
  75101. }
  75102. if (_this._captureRenderTargetsRenderTime) {
  75103. _this._renderTargetsRenderTime.fetchNewFrame();
  75104. }
  75105. if (_this._captureFrameTime) {
  75106. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  75107. _this._frameTime.beginMonitoring();
  75108. }
  75109. if (_this._captureInterFrameTime) {
  75110. _this._interFrameTime.endMonitoring();
  75111. }
  75112. if (_this._captureParticlesRenderTime) {
  75113. _this._particlesRenderTime.fetchNewFrame();
  75114. }
  75115. if (_this._captureSpritesRenderTime) {
  75116. _this._spritesRenderTime.fetchNewFrame();
  75117. }
  75118. if (_this._captureAnimationsTime) {
  75119. _this._animationsTime.beginMonitoring();
  75120. }
  75121. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  75122. });
  75123. // After render
  75124. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  75125. if (_this._captureFrameTime) {
  75126. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  75127. _this._frameTime.endMonitoring();
  75128. }
  75129. if (_this._captureRenderTime) {
  75130. _this._renderTime.endMonitoring(false);
  75131. }
  75132. if (_this._captureInterFrameTime) {
  75133. _this._interFrameTime.beginMonitoring();
  75134. }
  75135. });
  75136. }
  75137. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  75138. // Properties
  75139. /**
  75140. * Gets the perf counter used for active meshes evaluation time
  75141. */
  75142. get: function () {
  75143. return this._activeMeshesEvaluationTime;
  75144. },
  75145. enumerable: true,
  75146. configurable: true
  75147. });
  75148. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  75149. /**
  75150. * Gets the active meshes evaluation time capture status
  75151. */
  75152. get: function () {
  75153. return this._captureActiveMeshesEvaluationTime;
  75154. },
  75155. /**
  75156. * Enable or disable the active meshes evaluation time capture
  75157. */
  75158. set: function (value) {
  75159. var _this = this;
  75160. if (value === this._captureActiveMeshesEvaluationTime) {
  75161. return;
  75162. }
  75163. this._captureActiveMeshesEvaluationTime = value;
  75164. if (value) {
  75165. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  75166. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  75167. _this._activeMeshesEvaluationTime.beginMonitoring();
  75168. });
  75169. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  75170. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  75171. _this._activeMeshesEvaluationTime.endMonitoring();
  75172. });
  75173. }
  75174. else {
  75175. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  75176. this._onBeforeActiveMeshesEvaluationObserver = null;
  75177. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  75178. this._onAfterActiveMeshesEvaluationObserver = null;
  75179. }
  75180. },
  75181. enumerable: true,
  75182. configurable: true
  75183. });
  75184. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  75185. /**
  75186. * Gets the perf counter used for render targets render time
  75187. */
  75188. get: function () {
  75189. return this._renderTargetsRenderTime;
  75190. },
  75191. enumerable: true,
  75192. configurable: true
  75193. });
  75194. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  75195. /**
  75196. * Gets the render targets render time capture status
  75197. */
  75198. get: function () {
  75199. return this._captureRenderTargetsRenderTime;
  75200. },
  75201. /**
  75202. * Enable or disable the render targets render time capture
  75203. */
  75204. set: function (value) {
  75205. var _this = this;
  75206. if (value === this._captureRenderTargetsRenderTime) {
  75207. return;
  75208. }
  75209. this._captureRenderTargetsRenderTime = value;
  75210. if (value) {
  75211. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  75212. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  75213. _this._renderTargetsRenderTime.beginMonitoring();
  75214. });
  75215. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  75216. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  75217. _this._renderTargetsRenderTime.endMonitoring(false);
  75218. });
  75219. }
  75220. else {
  75221. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  75222. this._onBeforeRenderTargetsRenderObserver = null;
  75223. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  75224. this._onAfterRenderTargetsRenderObserver = null;
  75225. }
  75226. },
  75227. enumerable: true,
  75228. configurable: true
  75229. });
  75230. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  75231. /**
  75232. * Gets the perf counter used for particles render time
  75233. */
  75234. get: function () {
  75235. return this._particlesRenderTime;
  75236. },
  75237. enumerable: true,
  75238. configurable: true
  75239. });
  75240. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  75241. /**
  75242. * Gets the particles render time capture status
  75243. */
  75244. get: function () {
  75245. return this._captureParticlesRenderTime;
  75246. },
  75247. /**
  75248. * Enable or disable the particles render time capture
  75249. */
  75250. set: function (value) {
  75251. var _this = this;
  75252. if (value === this._captureParticlesRenderTime) {
  75253. return;
  75254. }
  75255. this._captureParticlesRenderTime = value;
  75256. if (value) {
  75257. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  75258. BABYLON.Tools.StartPerformanceCounter("Particles");
  75259. _this._particlesRenderTime.beginMonitoring();
  75260. });
  75261. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  75262. BABYLON.Tools.EndPerformanceCounter("Particles");
  75263. _this._particlesRenderTime.endMonitoring(false);
  75264. });
  75265. }
  75266. else {
  75267. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  75268. this._onBeforeParticlesRenderingObserver = null;
  75269. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  75270. this._onAfterParticlesRenderingObserver = null;
  75271. }
  75272. },
  75273. enumerable: true,
  75274. configurable: true
  75275. });
  75276. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  75277. /**
  75278. * Gets the perf counter used for sprites render time
  75279. */
  75280. get: function () {
  75281. return this._spritesRenderTime;
  75282. },
  75283. enumerable: true,
  75284. configurable: true
  75285. });
  75286. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  75287. /**
  75288. * Gets the sprites render time capture status
  75289. */
  75290. get: function () {
  75291. return this._captureSpritesRenderTime;
  75292. },
  75293. /**
  75294. * Enable or disable the sprites render time capture
  75295. */
  75296. set: function (value) {
  75297. var _this = this;
  75298. if (value === this._captureSpritesRenderTime) {
  75299. return;
  75300. }
  75301. this._captureSpritesRenderTime = value;
  75302. if (value) {
  75303. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  75304. BABYLON.Tools.StartPerformanceCounter("Sprites");
  75305. _this._spritesRenderTime.beginMonitoring();
  75306. });
  75307. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  75308. BABYLON.Tools.EndPerformanceCounter("Sprites");
  75309. _this._spritesRenderTime.endMonitoring(false);
  75310. });
  75311. }
  75312. else {
  75313. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  75314. this._onBeforeSpritesRenderingObserver = null;
  75315. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  75316. this._onAfterSpritesRenderingObserver = null;
  75317. }
  75318. },
  75319. enumerable: true,
  75320. configurable: true
  75321. });
  75322. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  75323. /**
  75324. * Gets the perf counter used for physics time
  75325. */
  75326. get: function () {
  75327. return this._physicsTime;
  75328. },
  75329. enumerable: true,
  75330. configurable: true
  75331. });
  75332. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  75333. /**
  75334. * Gets the physics time capture status
  75335. */
  75336. get: function () {
  75337. return this._capturePhysicsTime;
  75338. },
  75339. /**
  75340. * Enable or disable the physics time capture
  75341. */
  75342. set: function (value) {
  75343. var _this = this;
  75344. if (value === this._capturePhysicsTime) {
  75345. return;
  75346. }
  75347. this._capturePhysicsTime = value;
  75348. if (value) {
  75349. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  75350. BABYLON.Tools.StartPerformanceCounter("Physics");
  75351. _this._physicsTime.beginMonitoring();
  75352. });
  75353. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  75354. BABYLON.Tools.EndPerformanceCounter("Physics");
  75355. _this._physicsTime.endMonitoring();
  75356. });
  75357. }
  75358. else {
  75359. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  75360. this._onBeforePhysicsObserver = null;
  75361. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  75362. this._onAfterPhysicsObserver = null;
  75363. }
  75364. },
  75365. enumerable: true,
  75366. configurable: true
  75367. });
  75368. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  75369. /**
  75370. * Gets the perf counter used for animations time
  75371. */
  75372. get: function () {
  75373. return this._animationsTime;
  75374. },
  75375. enumerable: true,
  75376. configurable: true
  75377. });
  75378. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  75379. /**
  75380. * Gets the animations time capture status
  75381. */
  75382. get: function () {
  75383. return this._captureAnimationsTime;
  75384. },
  75385. /**
  75386. * Enable or disable the animations time capture
  75387. */
  75388. set: function (value) {
  75389. var _this = this;
  75390. if (value === this._captureAnimationsTime) {
  75391. return;
  75392. }
  75393. this._captureAnimationsTime = value;
  75394. if (value) {
  75395. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  75396. _this._animationsTime.endMonitoring();
  75397. });
  75398. }
  75399. else {
  75400. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  75401. this._onAfterAnimationsObserver = null;
  75402. }
  75403. },
  75404. enumerable: true,
  75405. configurable: true
  75406. });
  75407. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  75408. /**
  75409. * Gets the perf counter used for frame time capture
  75410. */
  75411. get: function () {
  75412. return this._frameTime;
  75413. },
  75414. enumerable: true,
  75415. configurable: true
  75416. });
  75417. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  75418. /**
  75419. * Gets the frame time capture status
  75420. */
  75421. get: function () {
  75422. return this._captureFrameTime;
  75423. },
  75424. /**
  75425. * Enable or disable the frame time capture
  75426. */
  75427. set: function (value) {
  75428. this._captureFrameTime = value;
  75429. },
  75430. enumerable: true,
  75431. configurable: true
  75432. });
  75433. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  75434. /**
  75435. * Gets the perf counter used for inter-frames time capture
  75436. */
  75437. get: function () {
  75438. return this._interFrameTime;
  75439. },
  75440. enumerable: true,
  75441. configurable: true
  75442. });
  75443. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  75444. /**
  75445. * Gets the inter-frames time capture status
  75446. */
  75447. get: function () {
  75448. return this._captureInterFrameTime;
  75449. },
  75450. /**
  75451. * Enable or disable the inter-frames time capture
  75452. */
  75453. set: function (value) {
  75454. this._captureInterFrameTime = value;
  75455. },
  75456. enumerable: true,
  75457. configurable: true
  75458. });
  75459. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  75460. /**
  75461. * Gets the perf counter used for render time capture
  75462. */
  75463. get: function () {
  75464. return this._renderTime;
  75465. },
  75466. enumerable: true,
  75467. configurable: true
  75468. });
  75469. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  75470. /**
  75471. * Gets the render time capture status
  75472. */
  75473. get: function () {
  75474. return this._captureRenderTime;
  75475. },
  75476. /**
  75477. * Enable or disable the render time capture
  75478. */
  75479. set: function (value) {
  75480. var _this = this;
  75481. if (value === this._captureRenderTime) {
  75482. return;
  75483. }
  75484. this._captureRenderTime = value;
  75485. if (value) {
  75486. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  75487. _this._renderTime.beginMonitoring();
  75488. BABYLON.Tools.StartPerformanceCounter("Main render");
  75489. });
  75490. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  75491. _this._renderTime.endMonitoring(false);
  75492. BABYLON.Tools.EndPerformanceCounter("Main render");
  75493. });
  75494. }
  75495. else {
  75496. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  75497. this._onBeforeDrawPhaseObserver = null;
  75498. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  75499. this._onAfterDrawPhaseObserver = null;
  75500. }
  75501. },
  75502. enumerable: true,
  75503. configurable: true
  75504. });
  75505. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  75506. /**
  75507. * Gets the perf counter used for frame time capture
  75508. */
  75509. get: function () {
  75510. return this.scene.getEngine()._drawCalls;
  75511. },
  75512. enumerable: true,
  75513. configurable: true
  75514. });
  75515. SceneInstrumentation.prototype.dispose = function () {
  75516. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  75517. this._onAfterRenderObserver = null;
  75518. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  75519. this._onBeforeActiveMeshesEvaluationObserver = null;
  75520. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  75521. this._onAfterActiveMeshesEvaluationObserver = null;
  75522. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  75523. this._onBeforeRenderTargetsRenderObserver = null;
  75524. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  75525. this._onAfterRenderTargetsRenderObserver = null;
  75526. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  75527. this._onBeforeAnimationsObserver = null;
  75528. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  75529. this._onBeforeParticlesRenderingObserver = null;
  75530. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  75531. this._onAfterParticlesRenderingObserver = null;
  75532. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  75533. this._onBeforeSpritesRenderingObserver = null;
  75534. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  75535. this._onAfterSpritesRenderingObserver = null;
  75536. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  75537. this._onBeforeDrawPhaseObserver = null;
  75538. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  75539. this._onAfterDrawPhaseObserver = null;
  75540. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  75541. this._onBeforePhysicsObserver = null;
  75542. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  75543. this._onAfterPhysicsObserver = null;
  75544. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  75545. this._onAfterAnimationsObserver = null;
  75546. this.scene = null;
  75547. };
  75548. return SceneInstrumentation;
  75549. }());
  75550. BABYLON.SceneInstrumentation = SceneInstrumentation;
  75551. })(BABYLON || (BABYLON = {}));
  75552. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  75553. var BABYLON;
  75554. (function (BABYLON) {
  75555. var _TimeToken = /** @class */ (function () {
  75556. function _TimeToken() {
  75557. this._timeElapsedQueryEnded = false;
  75558. }
  75559. return _TimeToken;
  75560. }());
  75561. BABYLON._TimeToken = _TimeToken;
  75562. })(BABYLON || (BABYLON = {}));
  75563. //# sourceMappingURL=babylon.timeToken.js.map
  75564. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","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#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture2D(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}"};
  75565. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\n","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  75566. (function universalModuleDefinition(root, factory) {
  75567. if (root && root["BABYLON"]) {
  75568. return;
  75569. }
  75570. var f = factory();
  75571. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  75572. globalObject["BABYLON"] = f;
  75573. if(typeof exports === 'object' && typeof module === 'object')
  75574. module.exports = f;
  75575. else if(typeof define === 'function' && define.amd)
  75576. define([], factory);
  75577. else if(typeof exports === 'object')
  75578. exports["BABYLON"] = f;
  75579. else {
  75580. root["BABYLON"] = f;
  75581. }
  75582. })(this, function() {
  75583. return BABYLON;
  75584. });